In the code below, the instance variable called "x" inside subclass "B" hides the instance variable also called "x" inside the parent superclass "A".
public class A {
public int x;
}
public class B extends A {
public int x;
}
In the code below, why does println(z.x) display the value of zero? Thanks.
A a = new A();
B b = new B();
a.x = 1;
b.x = 2;
A z = b;
System.out.println(z.x); // Prints 0, but why?

In the code below, why does println(z.x) display the value of zero?
Because it's referring to the z field declared in A... that's the only one that z.x can refer to, because the compile-time type of z is A.
The instance of B you've created has two fields: the one declared in A (which has the value 0) and the one declared in B (which has the value 2). The instance of A you created is entirely irrelevant; it's a completely independent object.
This is good reason to:
See more on this question at Stackoverflow