I got two classes. A Superclass and a Subclass.
public class SuperClass
{
protected int x;
public SuperClass(){
x=9;
}
public int getX(){
return this.x;
}
public Object getObject(){
return this;
}
}
public class SubClass extends SuperClass
{
private int x;
public SubClass(){
x = 1;
}
}
If I now create a subclass
SubClass sub = new SubClass();
and call the two methods, "this" references in the first method the superclass in the second the SubClass itself
sub.getX();
returns
9
which is the value of x of the superclass
sub.getObject();
on the other hand returns a reference to SubClass.
What's the reason for the two different references of "this", or am I missing something?
This shouldn't be duplicate of Overriding member variables in Java ( Variable Hiding) cause I'm wondering why "this" alone references the subclass not why this.x is giving me the variable of the superclass