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

    10-5-1: Given the following class definitions which of the following would not compile if it was used in place of the missing code in the main method?

    class Item
    {
       private int x;
    
       public void setX(int theX)
       {
          x = theX;
       }
       // ... other methods not shown
    }
    
    public class EnhancedItem extends Item
    {
       private int y;
    
       public void setY(int theY)
       {
          y = theY;
       }
    
       // ... other methods not shown
    
       public static void main(String[] args)
       {
          EnhancedItem currItem = new EnhancedItem();
          // missing code
       }
    }
    
  • currItem.setX(3);
  • The object currItem is an EnhancedItem object and it will inherit the public setX method from Item.
  • currItem.setY(2);
  • The object currItem is an EnhancedItem object and that class has a public setY method.
  • currItem.x = 3;
  • Even though an EnhancedItem object will have a x field the subclass does not have direct access to a private field. Use the public setX method instead.
  • currItem.y = 2;
  • All code in the same class has direct access to all object fields.

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

Next Section - 11.11. Inheritance and Constructors