Java Reference
In-Depth Information
33
34
// displays a Time1 object in 24-hour and 12-hour formats
35
private static void
displayTime(String header, Time1 t)
36
{
37
System.out.printf(
"%s%nUniversal time: %s%nStandard time: %s%n"
,
38
t.toUniversalString() t.toString()
header,
,
);
39
}
40
}
// end class Time1Test
After time object is created
Universal time: 00:00:00
Standard time: 12:00:00 AM
After calling setTime
Universal time: 13:27:06
Standard time: 1:27:06 PM
Exception: hour, minute and/or second was out of range
After calling setTime with invalid values
Universal time: 13:27:06
Standard time: 1:27:06 PM
Fig. 8.2
|
Time1
object used in an app. (Part 2 of 2.)
Calling
Time1
Method
setTime
with Invalid Values
To illustrate that method
setTime
validates
its arguments, line 23 calls method
setTime
with
invalid
arguments of
99
for the
hour
,
minute
and
second
. This statement is placed in
a
try
block (lines 21-24) in case
setTime
throws an
IllegalArgumentException
, which
it will do since the arguments are all invalid. When this occurs, the exception is caught at
lines 25-28, and line 27 displays the exception's error message by calling its
getMessage
method. Line 31 outputs the time again in both formats to confirm that
setTime
did
not
change the time when invalid arguments were supplied.
Software Engineering of the
Time1
Class Declaration
Consider several issues of class design with respect to class
Time1
. The instance variables
hour
,
minute
and
second
are each declared
private
. The actual data representation used
within the class is of no concern to the class's clients. For example, it would be perfectly
reasonable for
Time1
to represent the time internally as the number of seconds since mid-
night or the number of minutes and seconds since midnight. Clients could use the same
public
methods and get the same results without being aware of this. (Exercise 8.5 asks
you to represent the time in class
Time2
of Fig. 8.5 as the number of seconds since mid-
night and show that indeed no change is visible to the clients of the class.)
Software Engineering Observation 8.3
Classes simplify programming, because the client can use only a class's
public
methods.
Such methods are usually client oriented rather than implementation oriented. Clients are
neither aware of, nor involved in, a class's implementation. Clients generally care about
what
the class does but not
how
the class does it.