Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 595
user2911290 Avatar asked Oct 02 '22 06:10

user2911290


1 Answers

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
like image 128
Jon Skeet Avatar answered Oct 13 '22 10:10

Jon Skeet