简体   繁体   中英

super,this,static binding dynamic binding

Why super use static binding, but this use dynamic bind?
The code is on follows.

public class Person {
    public void method1() {
        System.out.print("Person 1");
    }
    public void method2() {
        System.out.print("Person 2");
    }
}

public class Student extends Person {
    public void method1() {
        System.out.print("Student 1");
        super.method1();
        method2();
    }
    public void method2() {
        System.out.print("Student2");
    }
}

public class Undergrad extends Student {
    public void method2() {
        System.out.print("Undergrad 2");
    }
}

When I enter follows in main method

Person u = new Undergrad();
u.method1();

The result is: Student 1 Person 1 Undergrad 2

This is not a trivial question as few other answers may have implied. There is descent explanation of this in Learning Java book :

The usage of the super reference when applied to overridden methods of a superclass is special ; it tells the method resolution system to stop the dynamic method search at the superclass, instead of at the most derived class (as it otherwise does).

When Undergrad calls method1(), since it is not overridden in Undergrad, method1() of Student gets called.

The questions focuses on these two lines in Student's method1:

    super.method1();
    method2();

Which is equivalent to:

    super.method1();
    this.method2();

Note: The dynamic object that called this function is Undergrad.

So in the second line - this.method2() will be dynamically bound to method2() of Undergrad. However in the first line - super.method1() won't be dynamically bound to Undergrad's super-class (which is Student), but will be statically (at compile time) bound to Student's parent (which is Person).

This is not as trivial as it seems, and the alternative (not correct) option of super.method1(); calling Undegrad's super class (Student) method1 is somewhat reasonable.

因为当从Student调用super.method1()时,意味着从Student的父类Person调用method1(),这不是super的工作原理吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM