user2911290
user2911290

Reputation: 1406

Instance variable hiding with inheritance

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?

Upvotes: 5

Views: 304

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503729

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

Upvotes: 4

Related Questions