Field hiding
There is a class hierarchy and on each level there is a field with same name publicName
.
Fields in subclasses can hide fields with the same name in their superclasses. This means that when you access a field using an instance of a subclass, the field in the subclass takes precedence, hiding the fields with the same name in its superclasses.
In the case of your grandPaSonActually
instance, which is an instance of the Son
class, the field publicName
from the Son
class takes precedence. So technically, when you access grandPaSonActually.publicName
, you are accessing the publicName
field from the Son
class, and its value is "SonName." This is known as field hiding.
While debuggers may show you the fields from the entire class hierarchy for inspection purposes, the actual field that is accessible and used when you access publicName
on grandPaSonActually
is the one defined in the Son
class. The fields from the superclasses (Father
and GrandPa
) are effectively hidden in this context.
So, to summarise, only the publicName
field from the Son
class ("SonName") is technically available and accessible in the grandPaSonActually
instance. The fields with the same name in the superclasses are hidden and not accessible through this instance.
Last updated
Was this helpful?