Understanding of Java polymorphism and dynamic binding

Source: Internet
Author: User

First, a section of the definition and concept of Baidu

What is polymorphic: 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. 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) 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. the role of polymorphism: to eliminate the coupling relationship between types.


And then I saw a subject like this.

Class A ... {Public String Show (D obj) ...           {return ("A and D"); Public String Show (A obj) ...           {return ("A and a"); }} class B extends A ... {Public String Show (B obj) ...           {return ("B and B"); Public String Show (A obj) ...           {return ("B and A"); }} class C extends B ... {} class D extends B ...          {}a A1 = new A ();          A A2 = new B ();          b b = new B ();           c C = new C ();           D d = new D ();   System.out.println (A1.show (b));   ①system.out.println (A1.show (c));   ②system.out.println (A1.show (d));   ③system.out.println (A2.show (b));   ④system.out.println (A2.show (c));   ⑤system.out.println (A2.show (d));    ⑥system.out.println (B.show (b));    ⑦system.out.println (B.show (c));    ⑧system.out.println (B.show (d)); ⑨answer:①a and A②a and A③  A and D④b and A⑤b and A⑥a and D⑦b and B⑧b and B⑨a and D 

The above concepts do not seem to be clear and do not help to understand the concept of polymorphism. At the end we will make a detailed analysis of the above questions.

Carry out the following practices:

Parent aparent = new Child ();

The Aparent method for dynamic binding is scoped to the method that is not covered by the child class in the parent class, and all methods of override in the child class. All of the methods in the child class that are not contained in the parent class are all removed (in fact, it is not possible to do so, and Aparent.method () cannot be compiled without the addition of the method in the parent. More on what to do).

PS: It is possible to visualize the aparent as an instance of child with an upward type conversion (parent), removing a method not defined in the parent class, and override the method in the parent class.

In this case, the polymorphic characteristics are mainly reflected in the method of the child class rewrite:

Class parent{....  Override_method () {} ....}

Class Child extends Parent .... {....  Overrride_method () {    System.out.print ("I ' m child.")  } ...} Class nephew extends Parent .... {....  Overrride_method () {    System.out.print ("I ' m nephew.")  } ...}

Parent aparent = new Child (); Parent bparent = new Nephew (); Aparent.override_method (); Bparent.override_method (); Output:i ' m child. I ' m nephew.

In the parent's reference downward with the same method, different sub-class instances will produce different methods of performance, is more intuitive polymorphic embodiment.

Step further into the details of the process:

1. What happens when a method call is made?

According to the search results, we can tell that the Override_method invocation process embodies the concept of dynamic binding.

First introduce the concept of method signature:

That is, the method definition of an object contains two parts: a method name and a parameter list. They collectively form the unique identity of a method.

Overload: The method name is the same in the same class, but the parameter list differs from the method definition called the method overload (overload)

Override: A method definition in a subclass that is exactly the same as a method name in a superclass is called overwrite (override)

PS: If a method definition in a subclass is just the same as a method name in a superclass, the method implementation in the superclass is not overwritten. The effect is similar to the result of a method overload.

2. The execution of the object method:

1. Assume that X is declared as an object of Class C, that is, c x = new C (); Call X.F (parameter p), then the compiler will enumerate the methods named F in all Class C and C's superclass in which the Access property is public and the method named F is not covered by the F in C.

2. Next, the compiler makes a check of the argument list provided when the method is called, if all of the methods named F have an exact matching parameter type, then choose this method, which is called overload resolution, but there may not be an exact match of the parameter type, the compiler will type the arguments passed in, If int can be converted to double, the subclass turns into a parent class (this behavior will retrieve the entire upward inheritance chain). If there is no match after the conversion, or if more than one method is found to match after the conversion, an error occurs.

3. When invoking a method with dynamic binding, the virtual machine must call the method of the class that is most appropriate for the actual type of the object referenced by X. Give a chestnut: Class D extends C, c x = new D (); Make a X.F (string) call, first if f (string) is defined in D, then the F (string) in D is called directly, and if there is no definition in D, then the F (string) is found in the superclass C and, if not, the entire inheritance chain is searched, and so on.

4. There is a dynamic binding, then the corresponding static binding: All private, Static, final method, or constructor method is the compiler can know exactly which method to call, called the static binding.

Let's take a look at the beginning of the question:

1.a1.show (b)

The type of the declaration reference is a, the actual object type is also a, the argument list is type B, contains the Show method for Show (D), Show (A), there is no exact match called show (b), the type of the incoming parameter is converted upward, B's superclass is a, the passed in parameter list is converted to a, Match Show (a), call Show (a)

Returns a and a.

2.a1.show (c)

The type of the declaration reference is a, the actual object type is also a, the argument list is type C, contains the Show method for Show (D), Show (A), there is no exact match called show (c), the type of the passed argument is converted upward, the superclass of C is b,b and there is no match, continue to convert upward to get A , b in the incoming argument list is converted to A, match Show (a), call Show (a).

Returns a and a

3.a1.show (d)

Ditto.

Returns a and a.

4.a2.show (b)

The declaration is referred to as type A, the actual instance type is B, the method called is show (b), first we look at Show,show (D) in A, show (a), and show (b) in B, Show (a) where show (a) override show (a) in a , Show (B) method does not exist in a, exclude. So the alternative is a.show (D), B.show (a), and the incoming parameter B is converted up to a, matching b.show (a)

Returns B and A

5.a2.show (c)

Ditto

6.a2.show (d)

The declaration is referred to as type A, the actual instance type is B, the method called is show (b), first we look at Show,show (D) in A, show (a), and show (b) in B, Show (a) where show (a) override show (a) in a , Show (B) method does not exist in a, exclude. So the alternative is a.show (d), B.show (A), matching a.show (d)

Returns a and D

7.b.show (b)

The declaration reference is B, the actual type is B, the method called is show (b), and the B.show (b) is called directly

Returns B and B.

8.b.show (c)

The declaration reference is B, the actual type is B, the method called is Show (C), there is no method match in B and superclass A, C is converted to B, match b.show (b)

Returns B and B

9.b.show (d)

The declaration reference is B, the actual type is B, the method called is show (d), the method in B does not match, but B's superclass a matches the method A.show (d)

Returns a and D

Understanding of Java polymorphism and dynamic binding

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.