Java Reference
In-Depth Information
public
private
Violate
encapsulation
Enforce
encapsulation
Variables
Support other
methods in the
class
Provide services
to clients
Methods
FIGURE 4.6
The effects of public and private visibility
Accessors and Mutators
Because instance data is generally declared with private visibility, a
class usually provides services to access and modify data values. A
method such as getFaceValue is called an accessor method because
it provides read-only access to a particular value. Likewise, a method
such as setFaceValue is called a mutator method because it changes
a particular value.
Generally, accessor method names have the form getX , where X is the value to
which it provides access. Likewise, mutator method names have the form setX ,
where X is the value they are setting. Therefore these types of methods are some-
times referred to as “getters” and “setters.”
For example, if a class contains the instance variable height , it should also prob-
ably contain the methods getHeight and setHeight . Note that this naming conven-
tion capitalizes the first letter of the variable when used in the method names, which
is consistent with how method names are written in general.
Some methods may provide accessor and/or mutator capabilities as a side effect
of their primary purpose. For example, the roll method of the Die class changes
the faceValue of the die and returns that new value as well. Note that the code
of the roll method is careful to keep the face value of the die in the valid range
(1 to MAX ). Service methods must be carefully designed to permit only appropriate
access and valid changes.
This points out a flaw in the design of the Die class. Note that there is no restric-
tion on the setFaceValue method—a client could use it to set the die value to a
number such as 20, which is outside the valid range. The code of the setFaceValue
KEY CONCEPT
Most objects contain accessor
and mutator methods to allow the
client to manage data in a controlled
manner.
 
Search WWH ::




Custom Search