In the below code snippet, the result is really confusing.
public class TestInheritance {
public static void main(String[] args) {
new Son();
This is commonly referred to as shadowing. Note your class declarations:
class Father {
public String x = "Father";
and
class Son extends Father {
public String x = "Son";
This creates 2 distinct variables named x
when you create an instance of Son
. One x
belongs to the Father
superclass, and the second x
belongs to the Son
subclass. Based on the output, we can see that when in the Father
scope, this
accesses the Father
's x
instance variable. So the behavior is not related to "what this
points to"; it's a result of how the runtime searches for instance variables. It only goes up the class hierarchy to search for variables. A class can only reference variables from itself and its parent classes; it can't access variables from its child classes directly because it doesn't know anything about its children.
To obtain the polymorphic behavior you want, you should only declare x
in Father
:
class Father {
public String x;
public Father() {
this.x = "Father"
}
and
class Son extends Father {
public Son() {
this.x = "Son"
}
This article discussed the behavior you're experiencing exactly: http://www.xyzws.com/Javafaq/what-is-variable-hiding-and-shadowing/15.