img
TABLE 9-1
Private
No Modifier
Protected
Public
Class Member
Same class
Yes
Yes
Yes
Yes
Access
Same
No
Yes
Yes
Yes
package
subclass
Same
No
Yes
Yes
Yes
package
non-subclass
Dif ferent
No
No
Yes
Yes
package
subclass
Dif ferent
No
No
No
Yes
package
non-subclass
specification, it is visible to subclasses as well as to other classes in the same package. This is
the default access. If you want to allow an element to be seen outside your current package,
but only to classes that subclass your class directly, then declare that element protected.
Table 9-1 applies only to members of classes. A non-nested class has only two possible
access levels: default and public. When a class is declared as public, it is accessible by any
other code. If a class has default access, then it can only be accessed by other code within its
same package. When a class is public, it must be the only public class declared in the file,
and the file must have the same name as the class.
An Access Example
The following example shows all combinations of the access control modifiers. This example
has two packages and five classes. Remember that the classes for the two different
packages need to be stored in directories named after their respective packages--in this
case, p1 and p2.
The source for the first package defines three classes: Protection, Derived, and SamePackage.
The first class defines four int variables in each of the legal protection modes. The variable n
is declared with the default protection, n_pri is private, n_pro is protected, and n_pub is
public.
Each subsequent class in this example will try to access the variables in an instance
of this class. The lines that will not compile due to access restrictions are commented out.
Before each of these lines is a comment listing the places from which this level of protection
would allow access.
The second class, Derived, is a subclass of Protection in the same package, p1. This
grants Derived access to every variable in Protection except for n_pri, the private one. The
third class, SamePackage, is not a subclass of Protection, but is in the same package and
also has access to all but n_pri.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home