Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

super,this,static binding dynamic binding

Tags:

java

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

like image 564
Bing Liang Avatar asked Nov 27 '25 13:11

Bing Liang


1 Answers

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.

like image 79
swupik Avatar answered Nov 29 '25 02:11

swupik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!