Java basics-polymorphism and java Polymorphism
Polymorphism allows different types of objects to correspond to the same message. With the advantages of flexibility, abstraction, behavior sharing, and code sharing, sharing means maximizing utilization and simplicity, and loading speed.
I. Role of Polymorphism
Eliminate coupling between types. That is, the same event will produce different results on different objects.
II. Implementation form of Polymorphism
1. Overload (occurs in the same class)
2. Overwrite (occurs in the subclass)
Iii. Benefits of Polymorphism
1. Alternative
2. scalability
3. Interface (polymorphism is a method signature that provides a common interface to the subclass)
4. Simplicity
5. Flexibility
Note: These benefits are relatively false. You can understand them only when they are actually applied.
4. three prerequisites for Polymorphism
1. There must be an inheritance relationship
2. Subclass override the method of the parent class
3. parent class references to subclass objects
Code example: Define a parent class Animal, a subclass Dog
1 // parent class -- Animal 2 public class Animal {3 int num = 44; 4 static int age = 2; 5 6 public void eat () {7 System. out. println ("animals need to eat"); 8} 9 10 public static void sleep () {11 System. out. println ("animals need to go to bed"); 12} 13 14 public void run () {15 System. out. println ("Long-legged animals love to run"); 16} 17}
1 // subclass -- Dog 2 public class Dog extends Animal {3 int num = 5; 4 static int age = 5; 5 String name = "Tom "; 6 7 public void eat () {8 System. out. println ("I love dog food"); 9} 10 11 public static void sleep () {12 System. out. println ("I Am a lively dog who doesn't like sleeping"); 13} 14 15 public void catchMouse () {16 System. out. println ("I like nosy"); 17} 18 19}
1 // test class 2 public class Demo_Test {3 public static void main (String [] args) {4 Animal a = new Dog (); 5. eat (); 6. sleep (); 7. run (); 8 9 System. out. println (. num); 10 System. out. println (. age); 11} 12}
Note:
From the preceding printed result (7), we can conclude that:
1) member variables: print the parent class, and the Child class does not exist;
2) member method: if the parent class is static, the parent class is printed. If the parent class is non-static, The subclass is printed directly;
3) An error is reported in the 5 and 6 columns on the left, because the method we use when calling static members is incorrect. (The following shows the correct one)
4) when you call a method not found in the parent class (a. catchMouse ();), an error is returned .)
At this time, polymorphism cannot use its own unique attributes and methods. This is the drawback of polymorphism. How can we solve this problem?
Answer: point this parent class reference to subclass object a, and then force it back to the Dog type. In this way, a is a reference of the Dog type and points to the Dog object.