protected: inheritance access
Understanding the protected access specifier requires a jump ahead. First, you should be aware that you don’t need to understand this section to continue through this book up through inheritance (Chapter 6). But for completeness, here is a brief description and example using protected.
The protected keyword deals with a concept called inheritance, which takes an existing class—which we refer to as the base class—and adds new members to that class without touching the existing class. You can also change the behavior of existing members of the class. To inherit from an existing class, you say that your new class extends an existing class, like this:
class Foo extends Bar {
The rest of the class definition looks the same.
If you create a new package and inherit from a class in another package, the only members you have access to are the public members of the original package. (Of course, if you perform the inheritance in the same package, you can manipulate all the members that have package access) Sometimes the creator of the base class would like to take a particular member and grant access to derived classes but not the world in general. That’s what protected does. protected also gives package access—that is, other classes in the same package may access protected elements.
If you refer back to the file Cookie.java, the following class cannot call the package-access member bite( ):
//: c05:ChocolateChip.java
// Can't use package-access member from another package.
import com.bruceeckel.simpletest.*;
import c05.dessert.*;
public class ChocolateChip extends Cookie {
private static Test monitor = new Test();
public ChocolateChip() {
System.out.println("ChocolateChip constructor");
}
public static void main(String[] args) {
ChocolateChip x = new ChocolateChip();
//! x.bite(); // Can't access bite
monitor.expect(new String[] {
"Cookie constructor",
"ChocolateChip constructor"
});
}
} ///:~
One of the interesting things about inheritance is that if a method bite( ) exists in class Cookie, then it also exists in any class inherited from Cookie. But since bite( ) has package access and is in a foreign package, it’s unavailable to us in this one. Of course, you could make it public, but then everyone would have access, and maybe that’s not what you want. If we change the class Cookie as follows:
public class Cookie {
public Cookie() {
System.out.println("Cookie constructor");
}
protected void bite() {
System.out.println("bite");
}
}
then bite( ) still has the equivalent of package access within package dessert, but it is also accessible to anyone inheriting from Cookie. However, it is not public.