What Protected Really Means

The “protected” access modifier says the member is visible to any classes in the same package, and to subclasses everywhere. The same package part is clear enough: your code is never in the same package as java.lang.Object.clone(). The “subclasses everywhere” part is more accurately expressed as a protected member can be accessed from within a class through references that are of at least the same type of the class. Consider this example, which uses a protected field called “teeth”, which is simpler to follow than the clone() method:

package animals;class Mammal {protected int teeth;  }package pets;class Cat extends Mammal { }class Dog extends Mammal {    Cat housemate = new Cat();    int cats_teeth = housemate.teeth; // NO!! field is protected. ...

Get Just Java™ 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.