This article describes the polymorphism of object-oriented programming in Java. Share it for your reference, as follows:
Polymorphism: Features that have the ability to express multiple forms (the same implementation interface uses different instances to perform different operations)
Advantages of implementing polymorphism: In order to facilitate unified calls!
Three ways to achieve polymorphism!
1. Conversion from subclass to parent class:
example:
Dog dog=new Dog("Euo","Schnauzer");dog.eat();Pet pet=new Dog("Euoo","Schnauzer");//Conversion from subclass to parent class pet.eat();pet.catchingFlyDisc();//Compilation error, reference of parent class cannot call the special method of subclassrule:
① Point a reference to a child class to an object called upward transformation and automatically perform type conversion.
② The method called by reference variables through the parent class is the child class overriding or inheriting the parent class's method, not the parent class's method.
③ At this time, the method unique to the subclass cannot be called by referencing variables through the parent class!
2. Use parent class as method formal parameters to implement polymorphism
public class Master{ private String name = ""; private int money = 0; public Master(String name, int money) { this.name = name; this.money = money; } public void feed(Pet pet) { pet.eat(); } public void feed(Dog dog) { dog.eat(); } public void feed(Penguin pen) { pen.eat(); }}public class Test(){ public static void main(String[] args) { Master master = new Master("Mr. Wang", 100); Pet pet = new Dog("Euro", "Schnauzer"); master.feed(pet); }}3. Use parent class as method return value to achieve polymorphism
public class Master{ private String name = ""; private int money = 0; public Pet getPet(int id) { Pet pet=null; if(id==1) { pet=new Dog("Europe","Schnauzer") } else if(id==2) { pet=new Penguin("Nana","Emperor Penguin"); } return pet; }}Notice:
① The existence of inheritance (Inheritance is the basis of polymorphism, without inheritance, there is no polymorphism)
② Methods of subclass rewriting parent class
③ Parent class references variables to subclass objects
For more Java-related content, readers who are interested in this site can view the topics: "Introduction and Advanced Tutorial on Java Object-Oriented Programming", "Tutorial on Java Data Structure and Algorithm", "Summary of Java Operation DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.