Java Reference
In-Depth Information
SR 4.8
What happens when you pass an object to a
print
or
println
method?
SR 4.9
What is the scope of a variable?
SR 4.10
What are UML diagrams designed to do?
We mentioned in our overview of object-oriented concepts in Chapter 1 that an
object should be
self-governing.
That is, the instance data of an object should be
modified only by that object. For example, the methods of the
Die
class should
be solely responsible for changing the value of the
faceValue
variable. We should
make it difficult, if not impossible, for code outside of a class to “reach in” and
change the value of a variable that is declared inside that class. This characteristic
is called
encapsulation.
An object should be encapsulated from the rest of the system.
It should interact with other parts of a program only through the
specific set of methods that define the services that that object pro-
vides. These methods define the
interface
between that object and the
program that uses it.
Encapsulation is depicted graphically in Figure 4.5. The code that uses an
object, sometimes called the
client
of an object, should not be allowed to access
variables directly. The client should call an object's methods, and those methods
then interact with the data encapsulated within the object. For example, the
main
method in the
RollingDice
program calls the
roll
method of the
Die
objects.
The
main
method should not (and in fact cannot) access the
faceValue
variable
directly.
KEY CONCEPT
An object should be encapsulated,
guarding its data from inappropriate
access.
Object
Interface
Client
Methods
Data
FIGURE 4.5
A client interacting with the methods of an object
Search WWH ::
Custom Search