Java Reference
In-Depth Information
T his chapter resumes our examination of classes and methods. It begins by explaining
how to control access to the members of a class. It then discusses the passing and returning
of objects, method overloading, recursion, and the use of the keyword static . Also de-
scribed are nested classes and variable-length arguments.
Controlling Access to Class Members
In its support for encapsulation, the class provides two major benefits. First, it links data
with the code that manipulates it. You have been taking advantage of this aspect of the class
since Chapter 4 . Second, it provides the means by which access to members can be con-
trolled. It is this feature that is examined here.
Although Java's approach is a bit more sophisticated, in essence, there are two basic
types of class members: public and private. A public member can be freely accessed by
code defined outside of its class. This is the type of class member that we have been using
up to this point. A private member can be accessed only by other methods defined by its
class. It is through the use of private members that access is controlled.
Restricting access to a class' members is a fundamental part of object-oriented program-
ming because it helps prevent the misuse of an object. By allowing access to private data
only through a well-defined set of methods, you can prevent improper values from being
assigned to that data—by performing a range check, for example. It is not possible for code
outside the class to set the value of a private member directly. You can also control pre-
cisely how and when the data within an object is used. Thus, when correctly implemented,
a class creates a “black box” that can be used, but the inner workings of which are not open
to tampering.
Up to this point, you haven't had to worry about access control because Java provides
a default access setting in which, for the types of programs shown earlier, the members
of a class are freely available to the other code in the program. (Thus, for the preceding
examples, the default access setting is essentially public.) Although convenient for simple
classes (and example programs in topics such as this one), this default setting is inadequate
for many real-world situations. Here you will see how to use Java's other access control
features.
Java's Access Modifiers
Member access control is achieved through the use of three access modifiers : public ,
private , and protected . As explained, if no access modifier is used, the default access set-
Search WWH ::




Custom Search