ref:http://www.studytonight.com/java/method-overriding-in-java.phpMethod 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'll implement the method again. As the example shows. The Dog CLSS gives its own implementation of Eat (). Method must has the same signature
Static method cannot be overriden.
Covariant return type
Since Java 5, it is possible to override a method by changing it return type, If subclass override any method by changing The return type of super class method,
Then the return type of Overriden method must is subtype of return type declared in Origin method inside the Supe R class. The only-to-which method can be overriden by chancing it 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 are OK here
difference between overloading and overriding
| Method Overloading |
Method overriding |
| Parameter must is 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 is more than restrictive than original method (can be less restrictive). |
Java Method overriding---runtime polymorphism! Not overloading