Java Reference
In-Depth Information
TIP: (continued)
Similar remarks apply to the method
precedes
in the same class. In one place in the
definition of
precedes
, we used
otherDate.getMonth()
rather than
otherDate.
month
only because we wanted the month as an integer instead of a string. We did, in
fact, use
otherDate.month
elsewhere in the definition of
precedes
.
■
TIP: Mutator Methods Can Return a Boolean Value
★
In the definition of the class
DateFifthTry
( Display 4.9 ), the mutator methods
tested to see if the new values for instance variables were sensible values. If they
were not, the mutator method ended the program and issued an error message. An
alternative approach is to have the mutator do the test, but to never have it end the
program. Instead, it returns a
boolean
value. It makes the changes to the instance
variables and returns
true
if the changes are sensible. If the attempted changes
are not sensible, the mutator method returns
false
. That way a programmer can
program in an alternative action to be taken if the attempted changes to instance
variables do not make sense.
For example, an alternative defi nition of the method
setMonth
of the class
DateFifthTry
( Display 4.9 ) is the following:
public boolean
setMonth(
int
monthNumber)
{
if
((monthNumber <= 0) || (monthNumber > 12))
return false
;
else
{
month = monthString(monthNumber);
return true
;
}
}
A sample use of this
boolean
valued version of
setMonth
could be the following:
DateFifthTry date =
new
DateFifthTry();
...
System.out.println("Enter month as a number:");
int
number = keyboard.nextInt();
while
(!date.setMonth(number))
{
System.out.println("Not a legal month number. Try again.");
System.out.println("Enter month as a number:");
number = keyboard.nextInt();
}
■