Java Reference
In-Depth Information
possibly without performing appropriate validation beforehand. By having the
object take responsibility for validating any potential change, value assignment
for attributes have a single point of control — within the object itself.
The autoExpires Accessor and Mutator Methods
Figure 9-11 displays the accessor method and mutator method for the
autoExpires instance variable of the Password class.
57
public boolean getAutoExpires ()
58
{
59
return autoExpires;
60
}
61
62
public void setAutoExpires ( boolean autoExpires )
63
{
64
this .autoExpires = autoExpires;
65
if ( autoExpires )
66
remainingUses = maxUses;
67
FIGURE 9-11
Both methods are quite short. The accessor method, getAutoExpires(), in
lines 57 through 60 returns the value of the instance variable, autoExpires. The
mutator method, setAutoExpires(), in lines 62 through 67, sets the value of the
instance variable to the value retrieved from the parameter. Because the variables
are of the boolean data type, the parameter does not need to be validated; it can
have only the value of either true or false, both of which are valid.
The code may be somewhat confusing, however, in that the parameter
in line 62 and the corresponding instance variable have the same name,
autoExpires. This is a legal and an acceptable way to code the mutator method,
setAutoExpires(). Because of the scope of local variables, as discussed earlier,
the passed parameter or local variable — defined in the parameter list in
line 62 — takes precedence over the instance variable with the same name.
Consequently, any use of the variable name, autoExpires, using just the name
of the variable refers to the local variable — that is, the parameter, and not the
instance variable. To differentiate and refer to the instance variable, program-
mers must specify a reference to the current object along with the variable name.
The keyword, this , in line 64 provides an explicit reference to the current object
within the class. To illustrate, if the assignment statement were coded
autoExpires = autoExpires;
it simply would assign the value of the parameter back to itself. No error would
occur, but the instance variable would not be changed. This is a common logic
error with beginning Java programmers. The statement can be corrected in one
of two ways. The first is to use the reference, this, with the instance variable, as in
this.autoExpires = autoExpires;
Search WWH ::




Custom Search