“this” keyword: Working mechanism in Java

前端 未结 5 1086
执笔经年
执笔经年 2020-12-29 09:49

After learning Java for sometime, its the first time the use of this keyword has confused me so much.

Here is how I got confused. I wrote the following

5条回答
  •  借酒劲吻你
    2020-12-29 10:30

    Why x and this.x point to the x of base class and not the Child class?

    Because fields in Java are not polymorphic. Fields binding is resolved at compilation time. If you wanted to use incrementing as polymorphism you could do it with a method. To perform correctly you would need to define it in parent and child.

    public void increment(){
        x++; //this.x++; would do the same;
    }
    

    And if this.x points to the x of the base class, why this.b() calls the b() of child class?

    Because methods on the other hand are polymorphic, which means their binding is resolved at run-time and that's why this.b() calls method from the child class, in your case this is instance of BasicInheritanceTest3 and corresponding method is called.

    Is the behavior of this different for fields and methods?

    As you see it is.

    Super is a reference to base class, so you can access it when for example needing to call overridden methods or/and hidden fields.

    EDIT Reply: this is a reference which means it is only address of the object along with all it's data in memory of JVM, how JVM handles this keyword is not really known or important, it is probably declared at instantiation. But all you need to know in the end is that this is reference to instance of Object himself.

提交回复
热议问题