Let's understand these lines of code:
a = new B();
a.test();
System.out.println(a.x);
- You create a new object of
B
. It will re-initialize the variable -A.x = 0
andB.x = 0
. - Then you invoke
a.test()
, which will call the overridden methodtest()
in classB
, which will setB.x
to2
usingthis.x = 2;
. Note at this point,A.x
is still0
. - Then you access
a.x
, which will access the fieldx
in classA
. The fields are not polymorphic. You don't override fields, but you hide them. The variablex
inB
hides the variablex
inA
.