Java polymorphism (polymorphic), dynamic bind (dynamically binding), late binding (late binding)

Source: Internet
Author: User

Today, we are talking about the most important thing in Java object-oriented, polymorphic. Polymorphism allows us to maximize the reusability of our programs, which is why we learn polymorphism.

"Polymorphic" (polymorphic) is also called "dynamic binding", also called "Late binding" (late binding).

Dynamic binding refers to "the actual type of the referenced object is judged during execution, not during compilation, and its corresponding method is called according to its actual type." ”

Program code:

 Public classtestpolymorphic{ Public Static voidMain (String args[]) {Animal Animal=NewAnimal ("Animal"); Cat Cat=NewCat ("Cat", "blue"); Dog Dog=NewDog ("Dog", "black"); Lily L1=NewLily ("L1", animal); Lily L2=NewLily ("L1", dog);        L1.myanimalenjoy ();    L2.myanimalenjoy (); }}classlily{PrivateString name; PrivateAnimal Animal;  PublicLily (String name, Animal Animal) { This. Name =name;  This. Animal =Animal; }     Public voidMyanimalenjoy () {Animal.enjoy (); }}classanimal{PrivateString name;  PublicAnimal (String name) { This. Name =name; }     Public voidenjoy () {System.out.println ("Sound"); }}classDogextendsanimal{PrivateString Forlorcolor;  PublicDog (String name,string forlorcolor) {Super(name);  This. Forlorcolor =Forlorcolor; }     Public voidenjoy () {System.out.println ("Dog Cry ~ ~ ~"); }}classCatextendsanimal{PrivateString Eyescolor;  PublicCat (String name,string eyescolor) {Super(name);  This. Eyescolor =Eyescolor; }     Public voidenjoy () {System.out.println ("Cat Cry ~ ~ ~"); }}

Program Run Result:

Summary: Through the above example, we found that the polymorphism must have three conditions 1, there is inheritance 2, there is a rewrite 3, the parent class reference to the Subclass object

Java polymorphism (polymorphic), dynamic binding, late binding (late binding)

Related Article

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.