Java Reference
In-Depth Information
for streaming audio devices. You still don't want the method generally available to ran-
dom objects (and so it shouldn't be public ), but you want the subclass to have access
to it.
Comparing Levels of Access Control
The differences among the various protection types can become confusing, particularly in
the case of protected methods and variables. Table 6.1, which summarizes exactly what
is allowed where, helps clarify the differences from the least restrictive ( public ) to the
most restrictive ( private ) forms of protection.
TABLE 6.1
The Different Levels of Access Control
Visibility
public
protected
default
private
From the same class
yes
yes
yes
yes
From any class in
yes
yes
yes
no
the same package
From any class
yes
no
no
no
outside the package
From a subclass in
yes
yes
yes
no
the same package
From a subclass
yes
yes
no
no
outside the same
package
Access Control and Inheritance
One last issue regarding access control for methods involves subclasses. When you cre-
ate a subclass and override a method, you must consider the access control in place on
the original method.
As a general rule, you cannot override a method in Java and make the new method more
restrictively controlled than the original. You can, however, make it more public. The fol-
lowing rules for inherited methods are enforced:
6
Methods declared public in a superclass also must be public in all subclasses.
n
Methods declared protected in a superclass must either be protected or public
in subclasses; they cannot be private .
n
Methods declared without access control (no modifier was used) can be declared
more private in subclasses.
n
Methods declared private are not inherited at all, so the rules don't apply.
 
Search WWH ::




Custom Search