next up previous
Next: Overriding of methods Up: Unit 08 Previous: Compatibility between actual and

Access to the public and private fields of the superclass

As we have seen, the derived class inherits all instance variables and all methods of the superclass.

Obviously, the public fields of the superclass are accessible from the derived class. For example, we can add to the subclass Student a method printName() as follows.

public class Student extends Person {
  ...
  public void printName() {
    System.out.println(this.getName());
  }
  ...
}

What about the private fields of the superclass? More precisely, are the methods defined in the derived class considered as any other client of the superclass, or do they have special privileges to access the private fields of the superclass? The answer is that the private fields of the superclass are not accessible to the methods of the derived class, exactly as they are not accessible to any other method outside the superclass.

For example, if we introduce in Student a method changeName() as follows, we get a compilation error.

public class Student extends Person {
  ...
  public void changeName(String s) {
    this.name = s; //ERROR! the instance variable name is private in Person
                   //hence, it is not accessible from the derived class Student
  }
  ...
}

Note: Java allows us to use, besides public and private fields, also fields of a different type, called protected. The protected fields of a class cannot be accessed by external methods, but they can be accessed by the methods of a derived class. We will not make use of protected fields in this course.


next up previous
Next: Overriding of methods Up: Unit 08 Previous: Compatibility between actual and