How does the “this” keyword in Java inheritance wo

2019-03-12 01:36发布

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

public class TestInheritance {
    public static void main(String[] args) {
        new Son();
        /*
        Father father = new Son();
        System.out.println(father); //[1]I know the result is "I'm Son" here
        */
    }
}

class Father {
    public String x = "Father";

    @Override
    public String toString() {
       return "I'm Father";
    }

    public Father() {
        System.out.println(this);//[2]It is called in Father constructor
        System.out.println(this.x);
    }
}

class Son extends Father {
    public String x = "Son";

    @Override
    public String toString() {
        return "I'm Son";
    }
}

The result is

I'm Son
Father

Why is "this" pointing to Son in the Father constructor, but "this.x" is pointing to "x" field in Father. How is the "this" keyword working?

I know about the polymorphic concept, but won't there be different between [1] and [2]? What's going on in memory when new Son() is triggered?

7条回答
一纸荒年 Trace。
2楼-- · 2019-03-12 02:01

While methods can be overridden, attributes can be hidden.

In your case, the attribute x is hidden: in your Son class, you can't access the Father's x value unless you use the super keyword. The Father class doesn't know about the Son's x attribute.

In the opposit, the toString() method is overriden: the implementation that will always be called is the one of the instantiated class (unless it does not override it), i.e. in your case Son, whatever the variable's type (Object, Father...).

查看更多
登录 后发表回答