public class A {
String bar = "A.bar";
A() { foo(); }
public void foo() {
System.out.println("A.foo(): bar = " + bar);
}
}
public class B extends A {
String bar = "B.bar";
B(){ foo(); }
public void foo(){
System.out.println("B.foo(): bar = " + bar);
}
}
public class C {
public static void main(String[] args){
A a = new B();
System.out.println("a.bar = " + a.bar);
a.foo();
}
}
Why does the first output has bar = null? Is it because B.foo() is being called before class B is created? if yes then how come B.foo() can be called? Or is it because the field bar in B.foo() is trying to get bar field from A but cannot access it?
My question is different from the one linked, i'm not asking about the call order ,i'm asking why does the first output is null? the other question is not about fields or null variables.
I don't understand how the bar variable in B.foo is null if it is defined in A and in B.