I am outputting
SubClass subClass = new SubClass(4);
System.out.println(subClass.getVal());
With these two classes:
public class SuperClass {
public int x = 99;
public int superClassMethod() {
return -1;
}
}
public class SubClass extends SuperClass {
public int x;
public SubClass(int value) {
x = value;
}
public int getVal() {
return x;
}
}
This outputs 4
as expected. But let's say I comment out the line x = value
in the SubClass
constructor. Why does it output 0
(I assume a default for uninitiated variables) and not 99
, inherited from the superclass?
If I change return x
to return superClassMethod();
it seems to correctly pull -1
from the superclass. So why the method and not the variable?
When variables have conflicting names from different scopes, it always uses the variable from the nearest scope, even if it isn't set to anything yet.
To distinguish variables in other scopes, prepend the variable with this
or super
:
public class SuperClass {
protected int x;
}
public class SubClass extends SuperClass {
private int x;
public SubClass(int x) {
x = 2; // sets the parameter variable
this.x = 2; // sets the instance variable
super.x = 2; // sets the super class' instance variable
}
}