Understanding of polymorphism in Java

Source: Internet
Author: User

At the beginning, polymorphism was also semi-known and semi-solution, and polymorphism was used recently, so I reviewed it again.

Polymorphism is a special type of inheritance.

For example

Class FatherClass

{

Function1 () {a1}

Function2 () {a2}

Function3 () {a3}

}

Class SonClass extends FatherClass

{

Function1 () {b1} // overwrite the parent class Method

Function2 () {b2} // overwrite the parent class Method

Function4 () {xx} // Add Method

}

FatherClass fc = new SonClass (); // The two types before and after are different and lead to polymorphism (it should be said that it is the type of the inheritance relationship, the former must be the parent class behind)

Fc. function1 (); // b1 Function

Fc. function2 (); // b2 Function

Fc. function3 (); // a3 Function

Fc. function4 (); // Error

 

 

 

The compile-time type of the parent class object, and the subclass is the runtime type.

Child classes inherit the methods of the parent class, because there are many child classes under the parent class, and there are various differences,

So the subclass will rewrite some methods provided by the parent class, so that the returned results of the subclass method are different from those of the parent class,

When the subclass method overwrites the parent class method, the reference object points to the subclass method attribute and the method that is not overwritten in the parent class,

The new special methods of subclass are not shown.

Simply put, the appearance of polymorphism leads to different results for transactions of the same parent class, thus reflecting multiple States ----> polymorphism !!

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.