Java Reference
In-Depth Information
Error-Prevention Tip 8.1
Most IDEs will issue a warning if you say
x
=
x;
instead of
this.x
=
x;
. The statement
x
=
x;
is often called a no-op (no operation).
Method
buildString
(lines 31-36) returns a
String
created by a statement that uses
the
this
reference explicitly and implicitly. Line 34 uses it
explicitly
to call method
toUni-
versalString
. Line 35 uses it
implicitly
to call the same method. Both lines perform the
same task. You typically will not use
this
explicitly to reference other methods within the
current object. Also, line 45 in method
toUniversalString
explicitly uses the
this
refer-
ence to access each instance variable. This is
not
necessary here, because the method does
not
have any local variables that shadow the instance variables of the class.
Performance Tip 8.1
Java conserves storage by maintaining only one copy of each method per class—this method
is invoked by
every
object of the class. Each object, on the other hand, has its own copy of
the class's instance variables. Each method of the class implicitly uses
this
to determine
the specific object of the class to manipulate.
Class
ThisTest
's
main
method (lines 6-10) demonstrates class
SimpleTime
. Line 8
creates an instance of class
SimpleTime
and invokes its constructor. Line 9 invokes the
object's
buildString
method, then displays the results.
As you know, you can declare your own constructor to specify how objects of a class should
be initialized. Next, we demonstrate a class with several
overloaded constructors
that en-
able objects of that class to be initialized in different ways. To overload constructors, sim-
ply provide multiple constructor declarations with different signatures.
Class
Time2
with Overloaded Constructors
The
Time1
class's default constructor in Fig. 8.1 initialized
hour
,
minute
and
second
to
their default
0
values (i.e., midnight in universal time). The default constructor does not
enable the class's clients to initialize the time with nonzero values. Class
Time2
(Fig. 8.5)
contains five overloaded constructors that provide convenient ways to initialize objects. In
this program, four of the constructors invoke a fifth, which in turn ensures that the value
supplied for
hour
is in the range 0 to 23, and the values for
minute
and
second
are each
in the range 0 to 59. The compiler invokes the appropriate constructor by matching the
number, types and order of the types of the arguments specified in the constructor call
with the number, types and order of the types of the parameters specified in each construc-
tor declaration. Class
Time2
also provides
set
and
get
methods for each instance variable.
1
// Fig. 8.5: Time2.java
2
// Time2 class declaration with overloaded constructors.
3
4
public class
Time2
5
{
Fig. 8.5
|
Time2
class with overloaded constructors. (Part 1 of 4.)