Field inheritance and field visibility are two separate concepts, not to be confused.
Field inheritance
In a way (to simplify a bit), a class is a template from making objects. So if a class A
declares two fields f1
and f2
, then instantiating A
creates objects (and allocates memory for them on the heap) that have these two fields.
A subclass is also a template for making objects, but this template is expressed as an addition to another class. So if class B
declares field f3
and extends A
, it's basically saying, "take all the fields that A
defines, and add f3
". So instantiating B
results in an object with three fields f1
, f2
, f3
.
Field Visibility
Field visibility, as expressed through access modifiers like private
and public
, is a way to control which part of the code "sees" (or can refer to) a certain field. The private
modifier means that no code outside of the class that declares the field can refer to this field. However, it doesn't mean that the field stops existing. To make a dodgy parallel, if you and another person are in a room and you turn off the light, you can't see the other person, but they are still there.
To emphasize the point that the concepts are separate, consider that in some cases you can see fields that are not inherited (e.g., because they are non-private, but in a class not in the same class hierarchy). And in some cases you can't see fields that are inherited, as in the case of private fields in the superclass.