Java Reference
In-Depth Information
Using Class
Time1
Class
Time1Test
(Fig. 8.2) uses class
Time1
. Line 9 declares and creates a
Time1
object
time
. Operator
new
implicitly invokes class
Time1
's default constructor, because
Time1
does not declare any constructors. To confirm that the
Time1
object was initialized prop-
erly, line 12 calls the
private
method
displayTime
(lines 35-39), which, in turn, calls the
Time1
object's
toUniversalString
and
toString
methods to output the time in univer-
sal-time format and standard-time format, respectively. Note that
toString
could have
been called implicitly here rather than explicitly. Next, line 16 invokes method
setTime
of the
time
object to change the time. Then line 17 calls
displayTime
again to output the
time in both formats to confirm that it was set correctly.
Software Engineering Observation 8.2
Recall from Chapter 3 that methods declared with access modifier
private
can be called
only
by other methods of the class in which the
private
methods are declared. Such meth-
ods are commonly referred to as
utility methods
or
helper methods
because they're typi-
cally used to support the operation of the class's other methods.
1
// Fig. 8.2: Time1Test.java
2
// Time1 object used in an app.
3
4
public class
Time1Test
5
{
6
public static void
main(String[] args)
7
{
8
// create and initialize a Time1 object
9
Time1 time =
new
Time1();
// invokes Time1 constructor
10
11
// output string representations of the time
12
displayTime(
"After time object is created"
, time);
13
System.out.println();
14
15
// change time and output updated time
16
time.setTime(
13
,
27
,
6
);
17
displayTime(
"After calling setTime"
, time);
18
System.out.println();
19
20
// attempt to set time with invalid values
21
try
22
{
23
time.setTime(
99
,
99
,
99
);
// all values out of range
24
}
25
catch
(IllegalArgumentException e)
26
{
27
System.out.printf(
"Exception: %s%n%n"
, e.getMessage());
28
}
29
30
// display time after attempt to set invalid values
31
displayTime(
"After calling setTime with invalid values"
, time);
32
}
Fig. 8.2
|
Time1
object used in an app. (Part 1 of 2.)