I'm pretty confused by the following code... Can somebody explain why overridden method getX() prints different result than getX_1(), and why it prints different result inside parent constructor, and outside the class ? (It's not a question about "polymorphic fields", cause no fields are accessed outside the class, it's about different behavior of methods that are invoked inside, or outside the constructor, and when actually instance fields are initialized).
public class TestInstanceVars {
public static void main(String[] args) {
C c = new C();
p("----- Third ----");
c.getX(); // 3 ... initilized!
}
private static void p(Object x){
System.out.println(x);
}
private static class A {
int x = 1;
A() {
p("----- First ----");
getX(); // 0 ... uninitialized ?
getX_1(); // 1 ... initialized ?
}
public int getX(){
p("Inside A::getX() ... x = " + x);
return x;
}
public int getX_1(){
p("Inside A::getX_1() ... x = " + x);
return x;
}
}
private static class B extends A {
int x = 2;
B() {
p("----- Second ----");
getX(); // 0 ... uninitialized
getX_1(); // 1 ... initialized ?
}
}
private static class C extends B {
int x = 3;
@Override
public int getX(){
p("Inside C::getX() ... x = " + x);
return x;
}
}
}