The polymorphism of the Java Foundation

Source: Internet
Author: User

What does polymorphism mean? The literal understanding is a variety of forms, that is, to the same object, there can be many different forms. Like sugar, there are a variety of flavors, you want to eat what flavor can eat what taste. But in the program, it's not what you want. It's more about how to do what you need to do. A more official explanation: in object-oriented languages, many different implementations of interfaces are polymorphic. Referring to Charlie Calverts's description of polymorphism--polymorphism is a technique that allows you to set a parent object to be equal to one or more of his sub-objects, after which the parent object can operate differently depending on the attributes of the child object currently assigned to it (excerpt from the "DELPHI4 Programming Insider"). To put it simply, it is a sentence: A pointer to the parent class type is allowed to be assigned a pointer to the child class type. Polymorphism is implemented through virtual functions in Object Pascal and C + +, and in Java, the implementation of polymorphism is implemented mainly through method overloading and method rewriting. In fact, when we say that we inherited a chapter, we have already used the feature of too many states, just to say that it has not been shown yet. Let's look at some of the classes we defined earlier:


You see, this is the two class we've set up before, it looks like an inheritance, right? In fact, if we do the following, you may find that there is something in it:

Action: Create a new test class that implements the following code:

If we simply look at the code on the right, we would say that this is an ordinary inheritance, but if you look closely at the code inside (the comment), you will find that in this test class, you do one of the following:

Animal giraffe =new Giraffe();

And this operation before we really have not seen before, have seen the most similar should also be this:

Giraffe giraffe =new Giraffe();

So, what's the difference between the two? In fact, although the two lines of code at the end of the results are the same, but there is a fundamental difference. Why is it? Because the former is the polymorphic we are going to introduce, the latter is simply the process of creating a giraffe object. Well, confused, why a variable of type animal can reference an object of type giraffe? This is because giraffe inherits some of the features of animal, and when we use Giraffe objects, we can actually understand the use of animal objects, but the difference is that the animal objects we can use are limited to only animal, If the part of animal is exceeded, it is taken as the Giraffe property of the time, and if we use a parent type to refer to the subclass object, the parent class method that is overridden in the subclass is accessed first (the method of the parent class is no longer executed), and the override in the parent class is executed if the subclass does not override the parent class's method At the same time, there is no part of the subclass that inherits from the parent class and cannot be executed. What do you mean? Code Explanation:
Modify subclass-related methods: Do not rewrite the Eat method in the animal class to increase the giraffe Run method:

Re-execute test with the following results:

Did you find it?we have not rewritten the Eat method in the newly modified giraffe, so it is executing the method in animal, and for the sleep method that has been overridden, the part of the subclass rewrite is executed. So what if we're going to execute the Run method? The results are as follows:

You see there's been a mistake,meaning that the Run method is not declared in the animal class
So, that's why we say:If we use a parent type to refer to a subclass object, the overridden parent method in the subclass is accessed first (the method of the parent class is no longer executed), and the overriding method in the parent class is executed if the child class does not override the parent class's methods. At the same time, there is no part of the subclass that inherits from the parent class and cannot be executed. And this kind of invocation, is a state of polymorphism, called upward transformation, is also the most easy to understand a polymorphic way.
So, since there is an upward transformation, there is also a downward transformation of nature. Then a classmate will say. The upward transformation is the subclass to the parent class, then the downward of course is the parent class rotor class, so Balabala, the code is modified to:

Giraffe giraffe =(Giraffe) new Animal();

Do you think that's right? The fact that we speak: Execute code:

We found that, no, there was a classcastexception anomaly, and the explanation was that the animal class could not be converted to giraffe class. It is wrong to explain the idea. So what is the right thing to do? is: The child class object that has been converted to the parent type, and then back to the subtype, is called downward transformation: WTF?? I want to first move up to the parent class, and then from the parent class down to the child class??? That's not just the same as calling a subclass Object! See here, believe this is the voice of most people. But in fact, there is a difference between the two, what is the difference? Is that we can make some changes to the upcoming downward transformation in the process of upward transformation. What do you mean? Take a look at the example: we make some changes to the animal class and the giraffe, adding a property count, which indicates how many meals were eaten. The code is as follows:
Animal class:

Package classtest;//animal class public class Animal { Span class= "Hljs-comment" >//adds a Count property. and set the set and Get methods private int count; public int getCount () {return count; } public void setCount (int count) {this.count = Count;} void Eat () {System. Out.println ( "animals eat");} void sleep () {System. Out.println ( "sleeping Animals");}           

Next is the Giraffe class:

Package classtest;Giraffe class inheriting from the animal classPublicClassGiraffeExtendsAnimal {Add a Count propertyPrivateint count;Publicint getcount () {return count;} Span class= "Hljs-keyword" >public void setcount (int count" {this.count = Count;} //Override the construction method public Giraffe (int count) {super (); this.count = Count;} //override sleep method void sleep () {System.out.println (" Giraffes eat "+count+" Walton Grass "); } //Subclass added Method void run () {System.out.println (" giraffe Four legs run wild "); }} 

Let's start with the first test with the following code:

Discover and use

Giraffe giraffe = new Giraffe(1); 

There is no difference, don't be afraid, the next change:

Add code in the test class:

You see, after modifying the Count property of Giraffe, does it also affect the Count property of Giraffe2? This is actually the use of the first upward, and then the gap to achieve the data modification. Of course, this is just one way to move down, and actually it's more of a design pattern and generics that are applied in Java. These points of knowledge will help you to understand the role of polymorphism in future learning.
OK, next, let's take a summary of polymorphism:
1, whether it is the upward transformation, or downward transformation, we are involved in the sub-class and the parent class problem, that is, polymorphism must have an inheritance relationship

2, as said above, polymorphism is a variety of forms. That is, when we need to implement polymorphism, we need to have the method of the parent class overridden by the quilt class. Otherwise, if there is no method of rewriting, you can not see the characteristics of polymorphism, all according to the method of the parent class, it is better not to inherit, directly in the parent class to add the appropriate method, and then the instantiation of the good

3, whether it is the upward transformation or downward transformation, there is a common denominator, that is, the parent class to the child class object. Without this, there would be no polymorphism.

The manifestations of polymorphism are divided into two categories:
Static Dispatch , which is the overload of the method. Behave as a method with the same name and different parameters, there can be more than one method with the same name, as long as the parameters are inconsistent, we can call one according to the actual situation, so called static dispatch.
Dynamic Dispatch , which is the override of a method. behaves as if the same name has different execution actions. Only one method can appear, and the action inside the method changes dynamically. You can and can only invoke one method at a time. Because it is not selected by the character, so it is dynamic.

Turn from 54809876

The polymorphism of the Java Foundation

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.