Java Reference
In-Depth Information
Protected Access
The third level of access control is to limit a method and variable to use by the following
two groups:
Subclasses of a class
n
Other classes in the same package
n
You do so by using the protected modifier, as in the following statement:
protected boolean outOfData = true;
You might be wondering how these two groups are different. After
all, aren't subclasses part of the same package as their super-
class? Not always. An example is the JApplet class. It is a sub-
class of java.applet.Applet but is actually in the javax.swing
package. Protected access differs from default access this way;
protected variables are available to subclasses, even if they aren't
in the same package.
NOTE
This level of access control is useful if you want to make it easier for a subclass to
implement itself. Your class might use a method or variable to help the class do its job.
Because a subclass inherits much of the same behavior and attributes, it might have the
same job to do. Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.
Consider the example of a class called AudioPlayer that plays a digital audio file.
AudioPlayer has a method called openSpeaker() , which is an internal method that inter-
acts with the hardware to prepare the speaker for playing. openSpeaker() isn't important
to anyone outside the AudioPlayer class, so at first glance you might want to make it
private . A snippet of AudioPlayer might look something like this:
class AudioPlayer {
private boolean openSpeaker(Speaker sp) {
// implementation details
}
}
This code works fine if AudioPlayer isn't going to be subclassed. But what if you were
going to create a class called StreamingAudioPlayer that is a subclass of AudioPlayer ?
That class needs access to the openSpeaker() method to override it and provide support
Search WWH ::




Custom Search