Java Reference
In-Depth Information
Using Access Attributes
Let's start by considering classes that are in the same package. Within a given package, any class has direct
access to any other class name in the same package — for declaring variables or specifying method para-
meter types, for example — but the variables and methods that are members of that other class are not ne-
cessarily accessible. The accessibility of these is controlled by
access attributes
. The name of a class in one
package can be accessed from a class in another package only if the class to be accessed is declared as
pub-
lic
. Classes not declared as
public
can be accessed only by classes within the same package.
You have four possibilities when specifying an access attribute for a class member, and each possibility
has a different effect overall. The options you have for specifying the accessibility of a variable or a method
ATTRIBUTE PERMITTED ACCESS
No access attributeFrom methods in any class in the same package.
public
From methods in any class anywhere as long as the class has been declared as
public
.
Accessible only from methods inside the class. No access from outside the class at all.
private
From methods in any class in the same package and from any subclass anywhere.
protected
The table shows you how the access attributes you set for a class member determine the parts of the Java
environment from which you can access it. I will discuss subclasses in the next chapter, so don't worry about
these for the moment. I will describe how and when you use the
protected
attribute then. Note that
public
,
private
, and
protected
are all keywords. Specifying a member as
public
makes it completely accessible,
and at the other extreme, making it
private
restricts access to members of the same class.
This may sound more complicated than it actually is.
Figure 5-10
shows the access allowed between
classes within the same package.
Within a package such as
package1
in
Figure 5-11
,
only the
private
members of the class
Class1
can't
be directly accessed by methods in other classes in the same package. If you declare a class member to be
private
, it can be accessed only by methods in the same class.