How does the “this” keyword in Java inheritance work?

后端 未结 7 673
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 09:23

In the below code snippet, the result is really confusing.

public class TestInheritance {
    public static void main(String[] args) {
        new Son();
                


        
7条回答
  •  无人共我
    2021-02-02 10:00

    Polymorphic method invocations apply only to instance methods. You can always refer to an object with a more general reference variable type ( a superclass or interface ), but at runtime, the ONLY things that are dynamically selected based on the actual object (rather than the reference type) are instance methods NOT STATIC METHODS. NOT VARIABLES. Only overridden instance methods are dynamically invoked based on the real object’s type.

    So variable x has not polymorphic behaviour because IT WILL NOT BE SELECTED DYNAMICALLY AT RUNTIME.

    Explaining your code :

    System.out.println(this);
    

    The Object type is Son so toString() method's Overridden Son version will be invoked.

    System.out.println(this.x);
    

    Object type is not in picture here, this.x is in Father class so x variable's Father version will be printed.

    See more at: Polymorphism in java

提交回复
热议问题