Hiding instance variables of a class
Solution 1:
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:
- If
Parent.var
should not be visible toChild
, make itprivate
. - If
Parent.var
andChild.var
are two logically distinct variables, give them different names to avoid confusion. - If
Parent.var
andChild.var
are logically the same variable, then use one data member for them.
Solution 2:
The "point" of field hiding is merely to specify the behaviour of code which does give a variable the same name as one in its superclass.
It's not meant to be used as a technique to genuinely hide information. That's done by making the variables private to start with... I would strongly recommend using private variables in virtually all cases. Fields are an implementation detail which should be hidden from all other code.