Java Object-Oriented Programming polymorphism example,
This example describes the Java Object-Oriented Programming polymorphism. We will share this with you for your reference. The details are as follows:
Polymorphism:Features that present multiple forms of capabilities (the same implementation interface uses different instances to perform different operations)
Advantages of implementing polymorphism: To facilitate unified calling!
Three methods to achieve polymorphism!
1. Subclass to parent class conversion:
Example:
Dog dog = new Dog ("ou", "schenarui"); dog. eat (); Pet pet = new Dog ("ou", "schenarui"); // convert the Child class to the parent class pet. eat (); pet. catchingFlyDisc (); // compilation error. The reference of the parent class cannot call special methods of the subclass.
Rules:
① Direct a reference to a parent class to a subclass object, which is called upward transformation and automatically performs type conversion
② At this time, the method used to reference variables through the parent class is to override or inherit the method of the parent class, not the method of the parent class.
③ At this time, variables referenced through the parent class cannot call the method unique to the subclass!
2. Use the parent class as the method parameter 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 ("ou", "sinairui"); master. feed (pet );}}
3. Use the parent class as the return value of the method to implement 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 ("ou", "schenarui")} else if (id = 2) {pet = new Penguin ("Nana", "emperor Penguin ");} return pet ;}}
Note:
① Inheritance existence (inheritance is the basis of polymorphism, and there is no polymorphism without inheritance)
② Subclass Method for rewriting the parent class
③ The parent class references a variable pointing to a subclass object.
For more java-related content, refer to this topic: introduction to Java Object-Oriented Programming and advanced tutorials, Java data structure and algorithm tutorials, Java DOM node skills summaries, Java files and directories, and java cache operation tips
I hope this article will help you with java programming.