Java Reference
In-Depth Information
Using Access Attributes
Let's start by considering classes in the same package. Within a given package, any class has direct
access to any other class name - for declaring variables or specifying method parameter types, for
example - but the variables and methods that are members of that other class are not necessarily
accessible. The accessibility of these is controlled by access attributes . You have four possibilities when
specifying an access attribute for a class member, including what we have used in our examples so far -
that is, not to specify anything at all - and each possibility has a different effect overall. The options you
have for specifying the accessibility of a variable or a method in a class are:
Attribute
Permitted access
No access attribute
From methods in any class in the same package.
public
From methods in any class anywhere.
private
Only accessible from methods inside the class. No access from
outside the class at all.
protected
From methods in any class in the same package and from any sub-
class anywhere.
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. We will discuss sub-classes in the next chapter, so don't
worry about these for the moment. We will be coming back to 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. Look at the next diagram, which shows the access
allowed between classes within the same package.
Class1
Class2
SubClass1
OK
OK
OK
No
OK
OK
OK
No
int a;
public int b;
protected int c;
private int e;
Package1
Within a package such as package1 , only the private members of the class Class1 can't be directly
accessed by a method in another class in the same package. Declaring a class member to be private
limits its availability solely to methods in the same class.
Search WWH ::




Custom Search