Java Reference
In-Depth Information
2.3. Access Control
If every member of every class and object were accessible to every other
class and object then understanding, debugging, and maintaining pro-
grams would be an almost impossible task. The contracts presented by
classes could not be relied on because any piece of code could directly
access a field and change it in such a way as to violate the contract. One
of the strengths of object-oriented programming is its support for
encap-
sulation
and
data hiding.
To achieve these we need a way to control who
has access to what members of a class or interface, and even to the class
or interface itself. This control is specified with
access modifiers
on class,
interface, and member declarations.
All members of a class are always available to code in the class itself.
To control access from other classes, class members have four possible
access modifiers:
•
private
Members declared
private
are accessible only in the class
itself.
•
package
Members declared with no access modifier are accessible
in classes in the same package, as well as in the class itself. We
discuss packages and related accessibility issues in
Chapter 18
.
•
protected
Members declared
protected
are accessible in subclasses
of the class, in classes in the same package, and in the class itself.
•
public
Members declared
public
are accessible anywhere the class
is accessible.
The
private
and
protected
access modifiers apply only to members not to
the classes or interfaces themselves (unless nested). For a member to be
accessible from a section of code in some class, the member's class must
first be accessible from that code.
It is important to realize that access control is performed on a per-class
(or interface) level not on a per-object level. This means that members