Hiding instance variables of a class

In Java, data members are not polymorphic. This means that Parent.var and Child.var are two distinct variables that happen to have the same name. You’re not in any sense “overriding” var in the derived class; as you have discovered yourself, both variables can be accessed independently of one another.

The best way forward really depends on what you’re trying to achieve:

  1. If Parent.var should not be visible to Child, make it private.
  2. If Parent.var and Child.var are two logically distinct variables, give them different names to avoid confusion.
  3. If Parent.var and Child.var are logically the same variable, then use one data member for them.

Leave a Comment