In-depth understanding of polymorphism and dynamic binding java--

He quotes online article. Infringement deleted.

1. Polymorphic

First, what is polymorphism?

According to the definition, an object variable may indicate various types of actual phenomenon called polymorphism.

Or you can say, a class object reference variables which point can not be determined at the time of programming, to confirm to have to wait until this point to the object variable in the end what kind, what kind of method is invoked when the program is running, so you can not modify the code in the case, changing the specific binding target to run, so you can select multiple programs running, this is polymorphism.

For example, a Manager class inherits from the Employee class, and an Employee can refer to either a variable Employee class objects, also can refer to the Manager class, this behavior is called polymorphism .

Let's look at a piece of code:

Manager boss = new Manager();
Employee[] staff = new Employee[3];
staff[0] = boss;

In this code, staff [0] and boss refer to the same object. But the compiler will staff [0] is seen as an Employee object, mean, boss subclass can call, but the staff [0] and the unique method of the Manager class can not call.
Such as:

boss.setBonus(); // OK
staff[0].setBonus();// Error

This is because the type of staff [0] is the statement of the Employee class.

The same can not be assigned to a reference variable subclass of the superclass.
This is because a superclass can have many sub-categories, if the Manager class variables can reference the Employee class, then this variable can refer to other subclass of Employee, so calls will error when running other subclasses unique method.

Polymorphism is divided into multi-state and multi-state run compile time. Which compile-time polymorphism is static, mainly refers to the overloaded methods, to distinguish it in different ways depending on the parameter list, after editing by changes to two different methods, at run-time polymorphism is not. The run-time polymorphism is dynamic, it is dynamic binding by *** *** to achieve, what we call polymorphism.

2. Dynamic Binding

Similarly, to understand the multi-state dynamic binding will understand, then, what is the dynamic binding?

At runtime can automatically select which method to call the phenomenon known as dynamic binding.

2.1 Process method call

Here we first explain the process of the method call.

The following is assumed to call xf (args), x is an object of class C. The following is a detailed description of the calling process:

<1> View Objects statements compiler type and method names. Suppose call xf (param), and x is a C object class. Note: There may be multiple named f, but not the same type of method parameters, such as might exist f (int), f (long ). The compiler will enumerate all of the classes named f C method and its superclass and public access attribute named f methods (private superclass inaccessible).
In this case, the compiler has access to all candidate methods may be called.

<2> Next type parameter provides the time, the compiler will call the view method, if there is a match with the parameters provided in all types of methods called f, on the choice of this method. This process is called overloading resolution . For example, calls f ( "hello, world!" ), Then the compiler will select f (string) but not the other, but by allowing the cast (int can be converted into a double, Manager can be converted into Employee, etc.), this process It can be complex. If the compiler does not match the method parameter type find, or type-conversion methods found to have multiple match, an error is reported.
In this case, the compiler has been the method name and parameter types need to call.

<3> If this method is private, static, final method or constructor, the compiler will know exactly which method to call, we will call this way is called static binding . Corresponding thereto, the actual method called depends on the type of variable and dynamic run-time binding.

<4> When the program runs, and when using the dynamic binding method is called virtual machine must call the actual type of the object class that the most suitable method to the x-referenced , such as the actual type of x is D, D inherits from class C . So when you call f, first check the class D method f (String), not to go to find super class of D f (String), and so on.

Finally, since each call search method should be carried out, the time overhead is very large. Therefore, the virtual machine created in advance for each class a method table, which lists all the signatures of methods (ie method name and parameter types, return type is not included) and the actual method call. In this case, when the real call a method, a virtual machine only to find the table on the line. In the previous example, the method of the virtual machine to search for classes D, in order to find the calling f (String) method to match, this method can be both Df (String), there may be Xf (String). Where X is D, superclass. It should be reminded that, if invoked super.f (param), super-class method table compiler will implicitly search parameters.

3. For example

Let's look at an example, this is the classic example related polymorphism, taken from:
http://blog.csdn.net/thinkGhoster/article/details/2307001

public class A {
    public String show(D obj) {
        return ("A and D");
    }

    public String show(A obj) {
        return ("A and A");
    } 

}

public class B extends A{
    public String show(B obj){
        return ("B and B");
    }
    
    public String show(A obj){
        return ("B and A");
    } 
}

public class C extends B{

}

public class D extends B{

}

public class Test {
    public static void main(String[] args) {
        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));    ⑨     
    }
}

operation result:

 ①   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

3.1 Analysis:

①②③ is better understood, usually can not go wrong. ④⑤ a bit confused, why output is not "B and B" it? ! !

Let us look at the words on this blog:

When the type of super class object reference variable subclass object reference, is referenced and not referenced object type determines the variable whose members call the method, but this method must be invoked been defined in the superclass, that is method subclass coverage.
(However, if forced to convert superclass subclass, then you can call and add new subclasses superclass method does not have a.)
Actually involved here priority issues of method calls, in descending order of priority: this .show (O), super.show (O ), this.show ((super) O), super.show ((super) O).

Now list method table,
A Class:
Show (D obj) -> A.show (D obj)
Show (A obj) -> A.show (A obj)

B类:
show(B obj) ->B.show(B obj)
show(A obj) ->A.show(A obj)

Methods listed above are not complete, there are methods of Object not listed.

Now according to my own understanding to analyze ⑤, namely a2.show © procedure call:

<1> in 5, a2 declared class A, the compiler will a2 candidate extraction method may be called, i.e. show (D obj) and show (A obj).

<2> Next type parameter provided when the compiler view calling method, but neither show © show (D obj) does not belong to show (A obj), then A's superclass to find this.Show (( super) O), since there is no superclass a (except Object), so that the C type conversion, because C is a superclass of B, a, C can thus be converted into B, a.

<3> found here show (A obj) in A, the method of analyzing the calling procedure <4>, i.e. when the program is run, and invoke methods using dynamic binding . The virtual machine must call the object's actual type of the most suitable method of that class and the referenced x , a2 because it is a reference to the class B and class B overrides the show (A obj), thus eventually calls subclass of class B show (A obj) method, the result is B and A.

Of course, the interpretation of <3> can also be referenced on the blog:

When the type of super class object reference variable subclass object reference, is referenced and not referenced object type determines the variable whose members call the method, but this method must be invoked been defined in the superclass, that is method subclass coverage.

To understand.

Dynamic binding of a very important feature : no need to modify existing code, you can extend the program. It is assumed to add a new class Executive, and the variable e possible to refer to objects of this class, no need to call the method comprising recompiled. Virtual automatically call the method of this class.

Above, I do reading notes, hoping you understand polymorphism and dynamic binding helpful.

Caishuxueqian for reference purposes only, If you have questions or suggestions, please put forward, progress together.

Guess you like

Origin blog.csdn.net/RebelHero/article/details/78757311