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)