Java Reference
In-Depth Information
111
112
// get second value
113
public int
getSecond()
114
{
115
return
second;
116
}
117
118
// convert to String in universal-time format (HH:MM:SS)
119
public
String toUniversalString()
120
{
121
return
String.format(
122
"%02d:%02d:%02d"
, getHour(), getMinute(), getSecond());
123
}
124
125
// convert to String in standard-time format (H:MM:SS AM or PM)
126
public
String toString()
127
{
128
return
String.format(
"%d:%02d:%02d %s"
,
129
((getHour() ==
0
|| getHour() ==
12
) ?
12
: getHour() %
12
),
130
getMinute(), getSecond(), (getHour() <
12
?
"AM"
:
"PM"
));
131
}
132
}
// end class Time2
Fig. 8.5
|
Time2
class with overloaded constructors. (Part 4 of 4.)
Class
Time2
's Constructors—Calling One Constructor from Another via
this
Lines 12-15 declare a so-called
no-argument constructor
that's invoked without arguments.
Once you declare any constructors in a class, the compiler will
not
provide a
default construc-
tor
. This no-argument constructor ensures that class
Time2
's clients can create
Time2
objects
with default values. Such a constructor simply initializes the object as specified in the con-
structor's body. In the body, we introduce a use of
this
that's allowed only as the
first
state-
ment in a constructor's body. Line 14 uses
this
in method-call syntax to invoke the
Time2
constructor that takes three parameters (lines 30-44) with values of 0 for the
hour
,
minute
and
second
. Using
this
as shown here is a popular way to
reuse
initialization code provided
by another of the class's constructors rather than defining similar code in the no-argument
constructor's body. We use this syntax in four of the five
Time2
constructors to make the class
easier to maintain and modify. If we need to change how objects of class
Time2
are initialized,
only the constructor that the class's other constructors call will need to be modified.
Common Programming Error 8.2
It's a compilation error when
this
is used in a constructor's body to call another of the
class's constructors if that call is not the first statement in the constructor. It's also a com-
pilation error when a method attempts to invoke a constructor directly via
this
.
Lines 18-21 declare a
Time2
constructor with a single
int
parameter representing the
hour
, which is passed with 0 for the
minute
and
second
to the constructor at lines 30-44.
Lines 24-27 declare a
Time2
constructor that receives two
int
parameters representing the
hour
and
minute
, which are passed with 0 for the
second
to the constructor at lines 30-
44. Like the no-argument constructor, each of these constructors invokes the constructor
at lines 30-44 to minimize code duplication. Lines 30-44 declare the
Time2
constructor