Key Points of Java + polymorphism-dynamic binding

Source: Internet
Author: User

Parent class


========================================================== ======================================

Public Class fruit {

 
Public void eat (){

System. Out. println ("I wanna eat fruit ");

}

}

-----------------------------------------------------------------------------

Public class AppleExtendsFruit {

Public void eat (){

System. Out. println ("I wanna eat apple ");

}
}
Public class orangeExtendsFruit {

Public void eat (){

System. Out. println ("I wanna eat orange ");

}

}
Bytes --------------------------------------------------------------------------------------

Test class

Bytes -------------------------------------------------------------------------------------

Public class testbind {

Public static void chose (fruit f ){
F. Eat ();
}

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub

Fruit A = new Apple ();

Fruit o = new orange ();
Testbind. chose ();
Testbind. chose (O );

}

}

Output result:

I wanna eat apple
I wanna eat orange

Bytes --------------------------------------------------------------------------------------

Dynamic binding: determines the actual type of the referenced object during execution (not during compilation) and calls the corresponding method based on the actual type.

The code above decides which instance method to call during the execution period.

--------------------------------------

In Java, except the static and final methods, all other methods are bound at runtime (also called post-binding. [Cannot be overwritten]

Private methods are implicitly specified as final. [The subclass cannot override the private method of the parent class]

Therefore, the final method is not bound at runtime.




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.