I have the following code: http://ideone.com/Ww5bd8
class A {
public int n = 1;
public int get() { return n; }
}
class B extends A {
public int n = 2;
public int get() { return n; }
}
class javaprog {
public static void main(String args[]) {
B b = new B();
A a = b;
System.out.println("a = b");
System.out.println(a.get());
System.out.println(a.n);
System.out.println(b.n);
}
}
This results in the output:
a = b
2
1
2
No A is ever created so how is the 2nd line which assigns 1 to n ever executed. Surely a and b are the same instance because of object references, and so in memory how can a.n refer to a different location than b.n?
If n was static I could understand this but it is an instance variable.