public Members
Public access is the least restrictive of all the access modifiers. A public member is accessible from anywhere, both in the package containing its class and by other packages where its class is accessible.
In Example 6.8, the public instance field pubInt in an instance of the class Superclass1 is accessible by all four clients. Subclasses can access their inherited public members by their simple names, and all clients can access public members in an instance of the class Superclass1.
protected Members
A protected member is accessible in all classes in the same package, and by all subclasses of its class in any package where its class is accessible.
In other words, a protected member cannot be accessed by non-subclasses in other packages. This kind of access is more restrictive than public member access.
In Example 6.8, the protected instance field proStr in an instance of the class Superclass1 is accessible within pkg1 by Client 1 and Client 2. Also as expected, Client 4—the class NonSubclass2 in pkg2—cannot access this protected member of the class Superclass1.
However, the compiler reports an error at (7) in the method printState1() of the class Subclass2 where the protected instance field proStr in an instance of the class Superclass1 cannot be accessed by the reference obj1.
In contrast, the method printState2() at (8) in the class Subclass2 uses the reference obj2 that refers to an instance of the class Subclass2 to access the instance fields declared in the class Superclass1, and now the protected instance field proStr in the superclass is accessible, as shown at (10).
This apparent anomaly is explained by the fact that a subclass in another package can only access protected instance members in the superclass via references of its own type—that is, protected instance members that are inherited by objects of the subclass. No inheritance from the superclass is involved in a subclass in another package when an object of the superclass is used.
Note that the above anomaly would not arise if a subclass in another package were to access any protected static members in the superclass, as such members are not part of any object of the superclass.