Understanding the polymorphism of Java methods

Source: Internet
Author: User

1. What is Java polymorphism

Browse the other People's blog in some of the introduction of polymorphic articles, found that everyone's description is a bit different, the main difference is whether to rewrite the method of multi-state. One of my more agreeable statements is as follows:

Polymorphism is divided into two types

A. Compile-time polymorphism: overloading of methods;

B. run-time polymorphism: the Java runtime system determines which method is called run-time polymorphism, depending on the type of instance that invokes the method. (We usually say a lot of things when the operation of polymorphic, so polymorphic mainly refers to the run-time polymorphism);

The above description holds that overloading is also a manifestation of polymorphism, although polymorphism mainly refers to runtime polymorphism.

2. Run-time polymorphism

A. The three main features of object-oriented : encapsulation, inheritance, polymorphism. From a certain point of view, encapsulation and inheritance are almost always prepared for polymorphism. This is our last concept, but also the most important point of knowledge.

B. polymorphic definition : means that objects of different classes are allowed to respond to the same message. That is, the same message can be used in a variety of different ways depending on the sending object. (Sending a message is a function call)

c. The technique of implementing polymorphism is called dynamic binding, which is the actual type of the referenced object that is judged during execution , and its corresponding method is called according to its actual type.

D. Polymorphism : Eliminate the coupling between types.

E. In reality, there are numerous examples of polymorphism. For example, if you press the F1 button, if the current pop-up in the Flash interface is the as 3 help document, if Word Help is currently popping up under Word, Windows Help and Support appears under Windows. The same event occurs on different objects and produces different results.

Here are the three necessary conditions for polymorphic existence, requiring you to recite them in a dream!

Three necessary conditions for polymorphic existence
First, to have inheritance;
Second, to have a rewrite;
The parent class reference points to the subclass object.

Benefits of polymorphism:

1. Replaceable (substitutability). Polymorphism is replaceable for existing code. For example, polymorphism works on the Circle Circle class and works on any other circular geometry, such as a ring.
2. expandability (Extensibility). Polymorphism has extensibility for code. Adding new subclasses does not affect the polymorphism, inheritance, and the operation and manipulation of other attributes of existing classes. In fact, new subclasses are more likely to get polymorphic functions. For example, it is easy to add the polymorphism of sphere class on the basis of realizing the multi-state of cone, semi-cone and hemispherical body.
3. Interface (interface-ability). Polymorphism is a superclass that, by way of signature, provides a common interface to subclasses, which is implemented by subclasses to refine or overwrite the class. As shown in 8.3. The super-Class shape in the figure specifies two interface methods for implementing polymorphism, Computearea () and Computevolume (). Subclasses, such as circle and sphere, refine or overwrite both interface methods in order to achieve polymorphism.
4. Flexibility (flexibility). It embodies the flexible operation in the application, and improves the use efficiency.
5. Simplification (simplicity). Polymorphism simplifies the process of coding and modifying the application software, especially when dealing with the operation and operation of a large number of objects.

3. Code Understanding

Looking at the above description, we probably know the following points:

A. Run-time polymorphism occurs when the parent class references a child class object. When a reference to a parent class can point to a multi-seed class object, how should the runtime respond to the same message? This is determined by the type of the actual object being referenced.

B. Why do you have to rewrite it? Is it not possible for a method in a parent class not to be overridden to invoke a method that exists directly in a subclass? Take a look at the following example:

In the above example, when GetName () in the parent class is commented out, calling the Father.getname () method will cause an error. Therefore, when a parent class reference points to a subclass method, the methods that exist in the parent class must be called, and if the method is overridden in a subclass, the method in the subclass is called dynamically at run time, which is polymorphic.

C. To have a good understanding of inheritance, without inheritance, where to rewrite it.

4. A bit deeper

After a basic understanding of polymorphism, we can see the following example, its output is what?

The answer is "son", which, combined with the previous explanations, is easy to judge. The GetName () method of the subclass overrides the method in the parent class, in main, the reference to the parent class father to the child object son, and when we call Father's GetName () method, it is actually dynamically bound to the GetName () of the subclass, so it prints " Son. "

5. A little Deeper

Do you really understand polymorphism? Take a look at the following example:

In the above example, what is the output of the following four statements?

A1.show (b);
A1.show (c);
A2.show (b);
A2.show (c);

The results are as follows:

For the results of the first two statements we can easily understand that the third and fourth, why the result and we think differently, should not be "B and B"? To understand why, we must first understand the following sentence:

When a Superclass object reference variable refers to a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass , that is, the method covered by the quilt class. (However, if you force the superclass to be converted to subclasses, you can call a method that is newly added in the subclass and the superclass does not.)

Look at the red sentence, do we know the problem?

When you run A2.show (b), you are actually calling a method of show (b obj), but is there a method in a? No! However, because B inherits from a, the method of Show (a obj) in a is called, but when the call finds that the method has been rewritten by B, it turns to call the show (a obj) method in B. So the "B and A" will be printed out.

In fact, this involves the priority of the method invocation, with the priority being high to Low:this.show (O), Super.show (O), This.show ((Super) O), Super.show ((Super) O). Let's take a look at how it works.

For example, A2.show (b), A2 is a reference variable, type A, then this is A2,b is an instance of B, so it went to class A to find the show (b obj) method, did not find, so to a super (super Class), and a No super class, So go to the third priority This.show (Super) O, this is still A2, here O is B, (super) O that is (super) B is A, so it goes to class A to find the method of show (a obj), Class A has this method, But since A2 refers to an object of Class B, B overrides the show (a obj) method of a, so it eventually locks to show (a obj) of Class B, and the output is "B and A".

What do you think? Do you understand?

The question goes on, now let's see how the above analysis process reflects the meaning of the words in the red font. It says that when a superclass object references a variable that references a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, that is, the method covered by the quilt class. Take A2.show (b) for a while.

A2 is a reference variable, type A, which refers to an object of B, so the meaning of this sentence is B to decide which method to invoke. Therefore, the show (b obj) of B should be called to output "B and B". But why is it inconsistent with the results from the previous analysis?! The problem is that we don't overlook the second half of the blue font, which is particularly important: the method that is called must be defined in the superclass, that is, the method covered by the quilt class. Does the show (b obj) inside B have a definition in super Class A? No! That's not to mention being covered. In fact, this statement hides a message: it is still determined by the priority of the method invocation. It finds show (a obj) in Class A, and if subclass B does not overwrite the show (a obj) method, then it calls the show (a obj) of a (because B inherits a, although it does not overwrite this method, but inherits this method from superclass a, in a sense, The method that is called is determined by B, except that the method is implemented in A); now subclass B overrides Show (a obj), so it eventually locks to show (a obj) of B. This is what the meaning of that sentence is, and here we can clearly understand the polymorphism of Java.

Understanding the polymorphism of Java methods

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.