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

后端 未结 7 672
被撕碎了的回忆
被撕碎了的回忆 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:08

    This is a behaviour done specially to have access to private members. So this.x looks at the variable X which is declared for Father, but when you pass this as a parameter to System.out.println in a method in Father - it looks at the method to call depending on the type of the parameter - in your case Son.

    So how do you call the super classes method? Using super.toString(), etc.

    From Father it cannot access the x variable of Son.

提交回复
热议问题