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 class testpolymorphic{public static void Main (String args[]) {Animal Animal = new Animal ("Animal"); Cat cat = new Cat ("Cat", "blue"); Dog dog = new Dog ("Dog", "Black"); Lily L1 = new Lily ("L1", animal); Lily L2 = new Lily ("L1", dog); L1.myanimalenjoy (); L2.myanimalenjoy (); }}class lily{private String name; Private Animal Animal; Public Lily (String name, Animal Animal) {this.name = name; This.animal = animal; } public void Myanimalenjoy () {Animal.enjoy (); }}class animal{private String name; Public Animal (String name) {this.name = name; } public void Enjoy () {System.out.println ("Scream ~ ~ ~"); }}class Dog extends animal{private String forlorcolor; Public Dog (String name,string forlorcolor) {super (name); This.forlorcolor = Forlorcolor; } public void Enjoy () {System.out.println ("dog cries ~ ~ ~"); }}class Cat ExtendS animal{private String eyescolor; Public Cat (String name,string eyescolor) {super (name); This.eyescolor = Eyescolor; } public void Enjoy () {System.out.println ("Cat cries ~ ~ ~"); }}
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 bind (dynamically binding), late binding (late binding)