Consider the following code.
class Base {
int i = 99;
public void amethod() {
System.out.println("Base.amethod()");
}
Base() {
this.amethod();
}
}
public class Derived extends Base {
int i = -1;
public static void main(String argv[]) {
Derived b; // here if we use **Base b;** below mentioned println() prints 99
b = new Derived();
System.out.println(b.i);
b.amethod();
}
public void amethod() {
System.out.println("Derived.amethod()");
}
}
output that i get
Derived.amethod()
-1 (99 when reference variable is of Base type)
Derived.amethod()
Now my question is
Since I am using only one 'new' keyword, only one object will get created (Which would be an instance of both Derived and base class),this object will have a single instance variable named i whose value should be same(as i think) whether one references it using Base class ref var or Derived class ref var.So how this i's value gets changed just by changing reference variable declaration(from Derived to Base) because i'm not changing anything in heap where objects get stored.
Hope I am clear in putting my question.