Java polymorphism and java Polymorphism

Source: Internet
Author: User
Tags money back

Java polymorphism and java Polymorphism

What is polymorphism in Java? It is also the concept of a paper tiger. The old routine is to embody it, differentiate it in detail, and first think about three problems (note that this is not a simple process, but a framework for thinking when learning a new concept ):

1. What is the purpose of this item? What is it? Where does it mean? (Obviously, if it is useless, there is no need to waste time; in fact, if you understand this problem, you will be able to grasp the problem by 50%)

2. How to use this concept or skill point? That is, its representation, such as keywords, modifiers, and syntaxes... (25%)

3. What are the key points and details of this application? (Yes, It also accounts for 25%)

The above three questions have been clarified, and the rest is used... "No, but he is familiar with it ."

 

I. First question: What is the purpose of polymorphism? What does it mean?

The role of polymorphism: Make the code loosely coupled to meet the open and closed principles. (Polymorphism means that an object has multiple features and can present different States under specific circumstances, thus corresponding to different attributes and Methods .) WTF? X again! What is loose coupling? What is the principle of still open and closed? Can I send it directly? Well, the so-called "coupling" means that when you expand the function, other source code corresponding to it should also be modified, which is a bit as ambiguous as the twist; "loose coupling" means that you do not need to modify other code even though you have extended it. In this way, the extension is opened and the modification is disabled.

Let's take a look at the specific example to understand: Xiaoqiang, a rural hot-blooded young man, came to work in a big city and spent some money every day working hard. Therefore, Xiaoqiang took the money back to his hometown and asked the matchmaker Wang daang in the village's east to introduce herself to her. Xiaoqiang waited anxiously for a few days and saw Wang's mother come over with a smile. "strong, I found a girl for you "...

Let's start with this story. We use code to implement this:

1 public class Girl {// parent class -- Girl 2 public int faceScore = 60; // face value 3 public int love = 0; 4 public void say () {// introduce yourself to 5 System. out. println ("hello world! "); 6} 7 public void addLove () {// after the request is made, added love value 8} 9} 10 public class HubeiGirl extends Girl {// subclass -- Hubei Girl 11 public int faceScore = 70; 12 public void say () {13 System. out. println ("My name is Xiaohong. I am very smart and can cook well. My love value: "+ love); 14} 15 public void addLove () {// rewrite add love Value Method 16 love + = 20; 17 System. out. println ("My love value is:" + love); 18} 19 public void cook () {// special method -- cooking 20 System. out. println ("red meatballs, fried meatballs, sixi meatballs... "); 21} 22} 23 public class HunanGirl extends Girl {// subclass -- Hunan Girl 24 public int faceScore = 85; 25 public void say () {26 System. out. println ("My name is Xiaoqian. I'm cute and can sing. My love value: "+ love); 27} 28 public void addLove () {// rewrite add love Value Method 29 love + = 10; 30 System. out. println ("My love value is:" + love); 31} 32 public void sing () {// special method -- singing 33 System. out. println ("Spicy girl ~ Spicy girl ~~ "); 34} 35}

The code is very simple. A girl's parent class has two child classes: Hubei girl and Hunan girl. Well, now Xiaoqiang sees two girls who want to express their love to them (after being loved, love value will increase). How can this problem be achieved? The Code is as follows:

1 public class XiaoQiang {// XiaoQiang class 2 public void courting (HubeiGirl B) {// express love to Hubei girl 3 B. addLove (); 4} 5 public void courting (HunanGirl n) {// express love to Hunan girl 6 n. addLove (); 7} 8} 9 public class Test {10 public static void main (String [] argrs) {11 HubeiGirl xiaohong = new HubeiGirl (); 12 xiaohong. say (); 13 HunanGirl xiaoqian = new HunanGirl (); 14 xiaoqian. say (); 15 XiaoQiang qiang = new XiaoQiang (); 16 qiang. courting (xiaohong); // Xiaoqiang expresses love to xiaohong, a girl in Hubei province. courting (xiaoqian); // Xiaoqiang expresses his love for xiaoqian, A Hunan girl. 18} 19}

Here we first define a small strong class, which contains two methods to express love. The parameters are different object types and are heavy loads. Create Xiaohong, Xiaoqian, and Xiaoqiang objects in the test class. The running result is as follows:

From the results, we can see that different object type parameters are passed in, and Xiaoqiang calls different methods to express love courting (). The requirements are met. bingo! The story continues. Wang's matchmaking career has already moved out of China and is developing internationally. She knows an African girl, mariica (for example), and wants to introduce mariica to Xiaoqiang... How can this be achieved? If you follow the above:

1 public class AfricaGirl extends Girl {// subclass -- African Girl 2 public int faceScore = 80; 3 public void say () {4 System. out. println ("My name is Marica. I am very enthusiastic and dancing. My love value: "+ love); 5} 6 public void addLove () {// rewrite add love Value Method 7 love + = 15; 8 System. out. println ("My love value is:" + love); 9} 10 public void dance () {// special method-dancing 11 System. out. println ("get started! Gogogogo for it! Get started! "); 12} 13} 14 public class XiaoQiang {// XiaoQiang class 15 public void courting (HubeiGirl B) {// express love to Hubei girl 16 B. addLove (); 17} 18 public void courting (HunanGirl n) {// express love to Hunan girl 19 n. addLove (); 20} 21 public void courting (AfricaGirl a) {// express love for African girls 22. addLove (); 23} 24}

This approach is to first define the sub-class African girl. This is required. In the small strong class, a courting (AfricaGirl a) method is added to achieve the requirements. However, there are two problems: 1. when the African girl category was added, the small strong category was changed, which was not loosely coupled and did not meet the open and closed principles. 2. if Wang's business is developing well, would you like to introduce 100 girls to Xiaoqiang? Would you like to change the Qiang class 100 times and add 100 methods to it?

So the question is: how can we define small strong classes so that we don't need to change small strong classes even if we keep increasing the number of girls? Polymorphism is used here, which is also the answer to the second question at the beginning.

 

2. Question 2: How to Use polymorphism?

In fact, the reference of the parent class points to the object of the subclass. Use the polymorphism idea to define the above small strong classes, as shown below:

1 public class XiaoQiang {// small strong class 2 public void courting (Girl g) {// The parameter is of the parent class type 3g. addLove (); 4} 5}

It is amazing that we can see that the method of using polymorphism is enough, just a method with the parameter of the parent class Girl type. Let's test it first:

1 public class Test {2 public static void main (String [] args) {3 HubeiGirl xiaohong = new HubeiGirl (); 4 xiaohong. say (); 5 HunanGirl xiaoqian = new HunanGirl (); 6 xiaoqian. say (); 7 AfricaGirl malika = new AfricaGirl (); 8 malika. say (); 9 XiaoQiang qiang = new XiaoQiang (); 10 qiang. courting (xiaohong); // Xiaoqiang expresses love to xiaohong, a girl in Hubei province. courting (xiaoqian); // Xiaoqiang expresses his love for xiaoqian, A Hunan girl. courting (malika); // Xiaoqiang expresses love to the African girl mariica 13 14} 15}

Function implementation, and no matter how many girls she introduced to Xiaoqiang, she does not need to modify Xiaoqiang class. So why can we achieve this effect by changing the parameter from the subclass type to the parent class type, that is, polymorphism?

Here, let's take a closer look.Use the parent class as the method parameter to implement PolymorphismTake the process of "Xiao qiang expresses love to African girl mariica" as an example, qiang. when courting (malika) is executed, as the object is used as a parameter, only the object is referenced. Therefore, the following occurs in the parameter section: Girl g = malika, that is to say, the reference g of the parent class Girl points to the subclass object malika (in some words, assign the pointer of the subclass type to the pointer of the parent class, which means, generally, pointers are the concepts in C and C ++. The call process is: when we useParent typeReference PointSubclass objectFirst, access the parent class method that is rewritten in the subclass (the method of the parent class will not be executed). If the subclass does not override the method of the parent class, the method in the parent class will be executed. This call method is a state of polymorphism calledUpward TransformationIs also the most understandable method of polymorphism. In the preceding example, the addLove () method rewritten in the AfricaGirl subclass is accessed first. If yes, the addLove () method in the parent Girl class is no longer accessed.

Well, the story goes on. The old man said: any fall in love that does not aim at marriage is a rogue. Xiaoqiang is a real person, so he wants to select a favorite girl and return the girl's object so that she can perform other operations... How can this requirement be met?

1 public class XiaoQiang {// small strong class 2 public void courting (Girl g) {// The parameter is of the parent class type 3g. addLove (); 4} 5 6 public Girl chooseGirl (int num) {// select the Girl's method, the returned value is Girl type 7 switch (num) {8 case 1: 9 HubeiGirl B = new HubeiGirl (); // If num is 1, return the b10 return B object of Hubei girl; 11 case HunanGirl n = new HunanGirl (); 13 return n; 14 case :15 AfricaGirl a = new AfricaGirl (); 16 return a; 17 default: 18 break; 19} 20 return null; 21} 22}

We can see that a method for selecting girls is added to the Xiaoqiang class, and different sub-class Girl objects are returned according to different numbers. The focus is that the returned value is the parent class Girl type, which isUse the parent class as the return value to implement Polymorphism. This is opposite to using the parent class as the method parameter to achieve polymorphism. Here, when the return value is used, the reference of the parent class type is directed to the subclass object. Call the following in Test:

1 public class Test {2 public static void main (String [] args) {3 XiaoQiang qiang = new XiaoQiang (); 4 Girl g = qiang. chooseGirl (1); // the return value is of the Girl type. Assign the return value to the reference g5 qiang of the Girl type. courting (g); // express love and increase the value of love by 6 GB. say (); 7} 8}

We can see that the number 1 is passed in, and the returned result is Xiaohong, a girl from Hubei Province. Since Xiaohong is very good at cooking, we can call her cooking method cook () as follows:

It seems that the cook () method is not well defined. Someone may ask if there is a cook () method in the subclass HubeiGirl, the problem is that the current g is a reference of the parent class Girl type, and the parent class Girl does not have the cook () method. This involves a feature of upward Transformation: After upward transformation, the reference of the parent class type can only call the override parent class method in the subclass and the method in the parent class, you cannot call special methods in the subclass. Here, cook () is the unique method of the subclass HubeiGirl, so it cannot be called.

What should I do if I marry a wife who can't cook? Here, we need to convert the returned parent type return value into a child type and assign it to the reference of the corresponding child type. As follows:

We can see that cook () is successfully called !, Convert the returned value of the parent class Girl type to the HubeiGirl type of the subclass, and then assign it to the reference g of the subclass HubeiGirl. Then, you can call the special methods of the subclass HubeiGirl. This process of converting a child type object to a parent type and then converting it back to the child type is calledDownward Transformation. (Note: you cannot directly convert a parent-type object to a child-type object. You must make a previous transition .)

Well, after the story is told, Xiaoqiang and Xiaohong have lived a happy life.

 

3. Question 3: What are the key points and details of using polymorphism?

The answer to this question is almost the same in No. 2 middle school. To sum up:

1.Inheritance: Polymorphism occurs in subclass and parent classes with inheritance relationships.

2.Rewrite: Polymorphism is a variety of forms. That is to say, when we need to implement polymorphism, we need to have a parent class method to overwrite the quilt class. Otherwise, if there is no override method, it will not be able to see the characteristics of polymorphism. It is better not to inherit everything according to the method of the parent class, simply add the corresponding method to the parent class, then it is instantiated.

3.Upward Transformation: The reference of the parent class type points to the object of the subclass.

4.Downward Transformation: The process of converting a child type object to a parent type and then converting it back to the child type.

5. There are two forms in Java to implement polymorphism, inheritance, and interfaces. The principle is the same. This article only describes inheritance.

 

Iv. Typical examples

Now that you have learned something, you have to use it. Otherwise, what is the purpose of learning something. The following is a typical example of polymorphism. You can try it without looking at the answer:

 1 public class A { 2     public String show(D obj) { 3         return ("A and D"); 4     } 5     public String show(A obj) { 6         return ("A and A"); 7     }  8 } 9 10 public class B extends A{11     public String show(B obj){12         return ("B and B");13     }   14     public String show(A obj){15         return ("B and A");16     } 17 }18 19 public class C extends B{20 21 }22 public class D extends B{23 24 }25 26 public class Test {27     public static void main(String[] args) {28         A a1 = new A();29         A a2 = new B();30         B b = new B();31         C c = new C();32         D d = new D();33         34         System.out.println("1--" + a1.show(b));35         System.out.println("2--" + a1.show(c));36         System.out.println("3--" + a1.show(d));37         System.out.println("4--" + a2.show(b));38         System.out.println("5--" + a2.show(c));39         System.out.println("6--" + a2.show(d));40         System.out.println("7--" + b.show(b));41         System.out.println("8--" + b.show(c));42         System.out.println("9--" + b.show(d));      43     }44 }

The running result is as follows:

1--A and A2--A and A3--A and D4--B and A5--B and A6--A and D7--B and B8--B and B9--A and D

I don't know how many people have done the right thing. Do you feel like Sherlock Holmes's case? Now let's wear a deer hunting cap, put a pipe on it, and start with a magnifier, first, let's take a look at the following picture that represents the four class relationships of ABCD:

You can see that:

1. show (A obj) in Class B inherits and overwrites the show (A obj) method in Class;

2. show (B obj) in Class B is a overload, and B is unique to;

3. B inherits the method of A, and C and D inherit the method of B (including the method of ).

Now let's look at it one by one:

1 ---- a1.show (B)

Subclass object B is used as the parameter, while a1 can only call the show (D obj) and show (A obj) methods. Obviously, show (A obj) is called, which is A typical multi-state application.

2 ---- a1.show (c)

Subclass Object c is used as the parameter. Similarly, a1 can only show (D obj) and show (A obj) methods. Obviously, show (A obj) is called ), in polymorphism, subclass objects can be referenced not only to the parent class, but also to the parent class. In Java, the ultimate parent class is Object. Therefore, Object references can point to any Object.

3 ---- a1.show (d)

Subclass Object d is used as the parameter. Similarly, a1 can only show (D obj) and show (A obj) methods, obviously... Yes, it contains the D type as the parameter method, so obviously show (D obj) is called ).

4 ---- a2.show (B)

A a2 = new B (); among them, a2 is A reference of the parent type pointing to the object of the subclass B type, which is A multi-state application. Therefore, a2 can call the following methods: show (D obj) in Class A and show (A obj) in Class B. Why can't I call the show (A obj) method in Class? Because subclass B has inherited and overwritten show (A obj) in Class A of the parent class, only show (A obj) in subclass B will be accessed ), no more access to show (A obj) in parent Class ). Why can't I call the show (B obj) method in Class B? Because this method is unique to subclass B, the reference a2 of the parent class A in polymorphism cannot be accessed. Now it is a2.show (B), and the parameter is subclass object B. Obviously, the show (A obj) method in Class B is called.

5 ---- a2.show (c)

Same as above, a2 can call two methods: show (D obj) in Class A and show (A obj) in Class B. The subclass Object c of B is used as the real parameter. Obviously, the show (A obj) method in Class B is called, and the parent type of the parent class of class C is used as the form parameter to realize polymorphism.

6 --- a2.show (d)

Same as above, a2 can call two methods: show (D obj) in Class A and show (A obj) in Class B. The subclass Object d of B is used as the real parameter, and the D type is used as the method of the form parameter. Therefore, the show (D obj) method in Class A is obviously called.

7 ---- B. show (B)

B B B = new B (); this is to call show (B obj) in Class B ).

8 ---- B. show (c) ------------------- it still needs to be determined based on the priority of the method called in the inheritance chain.

B B B = new B (); Class B inherits the methods of Class A. The methods that B can call include show (D obj) in Class) show (A obj) in Class B and show (B obj) in Class B. The subclass Object c of B is used as the real parameter, the show (B obj) in the parent class B is called, and the parent class is used as the form parameter for polymorphism. Why can't I call the show (A obj) method in Class B? Class A is the parent class of class C's parent class. Is it not allowed for Polymorphism to direct the reference of Class A to the object C of class c? Theoretically, but the actual situation is that there are two options: the parent class as the form parameter and the parent class as the form parameter to implement polymorphism. In this case, it is determined according to the priority of the method called in the inheritance chain. parent class B is higher than parent Class. The priority is: this. show (O), super. show (O), this. show (super) O), and super. show (super) O ).

9 ---- B. show (d)

Same as above, B can call the following methods: show (D obj) in Class A, show (A obj) in Class B, and show (B obj) in Class B) three methods... Yes, it contains the D type as the parameter method, so it is clear that show (D obj) in Class A is called ).

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.