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.