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?
While methods can be overridden, attributes can be hidden.
In your case, the attribute
x
is hidden: in yourSon
class, you can't access theFather
'sx
value unless you use thesuper
keyword. TheFather
class doesn't know about theSon
'sx
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 caseSon
, whatever the variable's type (Object
,Father
...).