«^»
7.4. Package members and protected members

Previously, we have declared members of classes to be either public or private. We look now at what it means for a member to have a protected modifier or to have no modifier at all.

If a member of a class has no modifier at all, it can be accessed by the code of any class within the same package. Such a member is sometimes called a package member.

If a member of a class has a protected modifier, it can be accessed by the code of any class within the same package or by the code of any subclass (whether or not it is in the same package).

So, the code of any method of a subclass may access any public and protected members of a superclass. Consider the class Person again. If we want some members of the class Person to be accessible in Person and in any subclass of Person but generally to be inaccessible, then those members can be protected members of the class Person. However, if we want a member of the class Person to be inaccessible in the code of the subclass, then it needs to be a private member of the class Person.

The class declaration for Person has oName and oDateOfBirth as protected fields and iHeight as a private field. So the code of a method of the class Student is able to access the fields oName and oDateOfBirth but is unable to access iHeight.

Some people argue that it is inappropriate for a subclass to be able to access fields of its superclass: they would argue that it is better for these fields to be private and for the superclass to provide public methods to access them.