Java Reference
In-Depth Information
Fig. 8.5. Line 12 invokes the single-argument constructor that takes a Time2 at lines 47-51
of Fig. 8.5. Next, the app displays the String representations of each Time2 object to con-
firm that it was initialized properly (lines 15-19). Line 24 attempts to initialize t6 by creating
a new Time2 object and passing three invalid values to the constructor. When the constructor
attempts to use the invalid hour value to initialize the object's hour , an IllegalArgumentEx-
ception occurs. We catch this exception at line 26 and display its error message, which re-
sults in the last line of the output.
1
// Fig. 8.6: Time2Test.java
2
// Overloaded constructors used to initialize Time2 objects.
3
4
public class Time2Test
5
{
6
public static void main(String[] args)
7
{
8
Time2 t1 = new Time2(); // 00:00:00
Time2 t2 = new Time2( 2 ); // 02:00:00
Time2 t3 = new Time2( 21 , 34 ); // 21:34:00
Time2 t4 = new Time2( 12 , 25 , 42 ); // 12:25:42
Time2 t5 = new Time2(t4); // 12:25:42
9
10
11
12
13
14
System.out.println( "Constructed with:") ;
15
displayTime( "t1: all default arguments" , t1);
16
displayTime( "t2: hour specified; default minute and second" , t2);
17
displayTime( "t3: hour and minute specified; default second" , t3);
18
displayTime( "t4: hour, minute and second specified" , t4);
19
displayTime( "t5: Time2 object t4 specified" , t5);
20
21
// attempt to initialize t6 with invalid values
22
try
23
{
24
Time2 t6 = new Time2( 27 , 74 , 99 ); // invalid values
25
}
26
catch (IllegalArgumentException e)
27
{
28
System.out.printf( "%nException while initializing t6: %s%n" ,
29
e.getMessage());
30
}
31
}
32
33
// displays a Time2 object in 24-hour and 12-hour formats
34
private static void displayTime(String header, Time2 t)
35
{
36
System.out.printf( "%s%n %s%n %s%n" ,
37
header, t.toUniversalString(), t.toString());
38
}
39
} // end class Time2Test
Constructed with:
t1: all default arguments
00:00:00
12:00:00 AM
Fig. 8.6 | Overloaded constructors used to initialize Time2 objects. (Part 1 of 2.)
Search WWH ::




Custom Search