This question is inspired by this other one I stumbled upon.
Given the following code:
public class Test {
public static void main(String[] args) {
Derived b = new Derived();
Base a = b;
System.out.println("b.i -> " + b.i);
System.out.println("a.i -> " + a.i);
System.out.println("b.getI() -> " + b.getI());
System.out.println("a.getI() -> " + a.getI());
}
}
class Base {
int i = 1;
public int getI() {
return i;
}
}
class Derived extends Base {
int i = 2;
public int getI() {
return -i;
}
}
// Output:
// b.i -> 2
// a.i -> 1
// b.getI() -> -2
// a.getI() -> -2
Could someone explain why a.i
is returning 1
? Shouldn't it be accessing i
field in Derived
class?
In addition, when debugging the code, I can see something like this:
There you can see that Derived
class is storing a reference to Base.i
.
Why is this happening? Shouldn't Base.i
be inherited and overwritten by Derived.i
?