This book is now obsolete Please use CSAwesome instead.

11.10. Access to Inherited Private FieldsΒΆ

Inheritance means that an object of the child class automatically includes the object fields and methods defined in the parent class. But, if the inherited fields are private, which they should be, the child class can not directly access the inherited fields using dot notation. The child class can use public accessors (also called getters) which are methods that get field values and public modifiers (also called mutators and setters) which set field values.

For example, if a parent has a private field, name, then the parent typically provides a public getName method and a public setName method as shown below. In the setName method below, the code checks if the passed string is null before it sets it and returns true if the set was successful or false otherwise. The Employee class inherits the name field but must use the public method getName and setName to access it.

Check your understanding

You can step through this code in the Java Visualizer by clicking on the following link Private Fields Example.

You have attempted of activities on this page