Manifestations of Polymorphism
1. What is polymorphism?
Object-orientedPolymorphismIt is the feature that applies the parent class object to the Child class object. To put it simply,PolymorphismIt refers to the "Duplicate name" Phenomenon in the application. Polymorphism allows you to write programs in a uniform style to process a wide range of existing and related classes. This not only reduces the difficulty of maintenance, but also saves time.
2. What are the aspects of polymorphism in java?
In instance 2.1, two show methods are defined in this class, but the formal parameters of the two methods are different. Therefore, the second show method reloads the first show method.
1/* define class TestPolymorphisml */2 public class TestPolymorphisml {3 4 String s = "this is an instance of method overloading"; 5 String ss = "This Is A TestPolymorphisml class "; 6 public void show () {7 System. out. println ("I'm the show method" + ss); 8} 9 public void show (String str) {// This method is an overload of the previous show method, with the same method name, they only need different 10 System parameters. out. println ("I have overloaded the show method" + str); 11} 12 public static void main (String [] args) {13 TestPolymorphisml test = new TestPolymorphisml (); 14 test. show (); // call the first show Method 15 test. show (test. s); // call the overloaded show Method 16} 17}
Running result:
Instance 2.2 first creates A new class A, then creates A class that inherits Class A, and overwrites the attributes and methods of the parent class in the subclass.
1/* define A class */2 public class A {3 String a = "I Am A class"; 4 public void showA () {5 System. out. println (a); 6} 7}
1/* define the class TestPolymorphism2 so that it inherits class A */2 public class TestPolymorphism2 extends A {3 String B = "I am rewriting method "; // This is the rewriting of the attribute of the parent class 4 public void showA () {// This is the rewriting of the showA method of the parent class 5 super. showA (); // use the keyword "super" to call the showA method of the parent class 6 System. out. println (B); 7} 8 public static void main (String [] args) {9 TestPolymorphism2 n = new TestPolymorphism2 (); // create object n10 n. showA (); 11} 12}
Running result:
In the experiment, we can clearly see how important polymorphism plays in java programming.