In Java, if a parent class and a child class have a field with the same name, the field doesn't override the parent's field.
When the compiler has to decide which field to use - the one declared in the parent or the one in the child - it does so based on the type of the reference variable being used. So, if you declared
ClassA instanceA;
Then whatever you assign to instanceA
, whether a real ClassA
or any child - if you write instanceA.a
, it means "the a
that was declared in ClassA
". If you declared:
ClassB instanceB;
Then whatever you assign to instanceB
(suppose, ClassB
also has children), the compiler will treat instanceB.a
as "the a
that was declared in ClassB
".
But the field is inherited, even if it is not overridden. That is, if you remove the declaration from ClassB
, then the compiler takes instanceB.a
to mean "the field a
that ClassB
inherited from ClassA
".
The term used for a field in a child class that has the same name as a field in a parent class is hiding (which is distinct from shadowing and obscuring - terms that are also used for certain situations in which the same name is used for two different items).