Method Overriding between parent and child
The key benefit of overriding is the ability to define method that's specific to a particular subclass type
class Animal
{
public void eat()
{
System.out.println("Generic Animal eating");
}
}
class Dog extends Animal
{
public void eat() //eat() method overriden by Dog class.
{
System.out.println("Dog eat meat");
}
}
The subclass will implement the method again. As the example shows. the Dog clss gives its own implementation of eat(). Method must have the same signature
Static method cannot be overriden.
Covariant return type
Since Java 5, it is possible to override a method by changing its return type, If subclass override any method by changing the return type of super class method,
then the return type of overriden method must be subtype of return type declared in origin method inside the super class. this is the only way by which method can be overriden by chancing its return type.
class Animal
{
Animal myType()
{
return new Animal();
}
}
class Dog extends Animal
{
Dog myType() //Legal override after Java5 onward
{
return new Dog();
}
}
Dog is a sub type of animal, therefore different return type is ok here
Difference between Overloading and Overriding
Method Overloading | Method Overriding |
---|---|
Parameter must be different and name must be same. | Both name and parameter must be same. |
Compile time polymorphism. | Runtime polymorphism. |
Increase readability of code. | Increase reusability of code. |
Access specifier can be changed. | Access specifier most not be more restrictive than original method(can be less restrictive). |