I stumbled upon this piece of code.
I tried to guess what will be the result of running it before actually doing so. I was really confused when I saw them & in need of some explanations.
This is the code:
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(); } } The output is:
B.foo(): bar = null B.foo(): bar = B.bar a.bar = A.bar B.foo(): bar = B.bar Why is that?
- How is
bar = null? - Why is
a.bar = A.bareven appear? I haven't instantiatedAat all. - And if
Aappears, why is it afterB?