Hiding Fields – Object-Oriented Programming

Hiding Fields – Object-Oriented Programming

Hiding Fields

A subclass cannot override inherited fields of the superclass, but it can hide them. The subclass can define fields with the same name as in the superclass. If this is the case, the fields in the superclass cannot be accessed in the subclass by their simple names; therefore, they are not inherited by the subclass. A hidden static field can always be accessed by using the superclass name in the subclass declaration. Additionally, the keyword super can be used in non-static code in the subclass declaration to access hidden static fields.

The following distinction between invoking instance methods on an object and accessing fields of an object must be noted. When an instance method is invoked on an object using a reference, it is the dynamic type of the reference (i.e., the type of the current object denoted by the reference at runtime), not the declared type of the reference, that determines which method implementation will be executed. In Example 5.2 at (15), (16), and (17), this is evident from invoking the overridden method energyCost(): The method from the class corresponding to the current object is executed, regardless of the declared reference type.

When a field of an object is accessed using a reference, it is the declared type of the reference, not the type of the current object denoted by the reference, that determines which field will actually be accessed. In Example 5.2 at (20), (21), and (22), this is evident from accessing the hidden field lightType: The field accessed is the one declared in the class corresponding to the declared reference type, regardless of the object denoted by the reference at runtime.

In contrast to method overriding, where an instance method cannot override a static method, there are no such restrictions on the hiding of fields. The field lightType is static in the subclass, but not in the superclass. The declared type of the fields need not be the same either—only the field name matters in the hiding of fields.