Java Method overriding---runtime polymorphism! Not overloading

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.