5

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?

1 Answer 1

4

In the code below, why does println(z.x) display the value of zero?

Because it's referring to the x 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:

  • Make all of your fields private, drastically reducing the possibility of hiding one field with another
  • Avoid hiding even where it's possible, as it causes confusion
Sign up to request clarification or add additional context in comments.

4 Comments

So if you were to set x in the superclass by passing the value trough the constructor, which the constructor passes it to the super class's constructor public B(int x) { super(x); }. Would the value then be different when initializing z and calling z.x?
@VinceEmigh: Well that would rely on the A constructor setting it too... and introducing a parameter called x as well makes things even more confusing. I suggest you just try it, to be honest.
Yeah, in class A: public int x; public A(int i) { x = i; }. I'm not on a computer right now, but I'll test it right when I get on one. It just seems like it would work as long as you set `int x' in the superclass aswell
@Vince: Yes, but they'll still be two independent variables which happen to start with the same value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.