Java Reference
In-Depth Information
The statement in Line 5 allocates memory space for a
Clock
object, initializes each instance
variable of the object to
0
, and stores the address of the object into
myClock
. The statement
in Line 6 allocates memory space for a
Clock
object; initializes the instance variables
hr
,
min
,
and
sec
of the object to
9
,
35
,and
15
, respectively; and stores the address of the object into
yourClock
(see Figure 8-2).
Reference
variable
Clock
object
Reference
variable
Clock
object
hr
0
hr 9
min 35
sec 15
myClock
yourClock
min
0
sec
0
FIGURE 8-2
Variables
myClock
and
yourClock
and associated
Clock
objects
To be specific, we call the object to which
myClock
points the object
myClock
and the
object to which
yourClock
points the object
yourClock
(see Figure 8-3).
Object myClock
Object yourClock
hr
0
hr
9
myClock
yourClock
min
0
min 35
sec 15
sec
0
FIGURE 8-3
Objects
myClock
and
yourClock
Of course, you can combine the statements to declare the variable and instantiate the object
into one statement. For example, the statements in Lines 1 and 5 can be combined as:
Clock myClock =
new
Clock();
//declare and instantiate myClock
That is, the preceding statement declares
myClock
to be a reference variable of type
Clock
and instantiates the object
myClock
to store the hours, minutes, and seconds. Each instance
variable of the object
myClock
is initialized to
0
by the default constructor.
Similarly, the statements in Lines 2 and 6 can be combined as:
Clock yourClock =
new
Clock(9, 35, 15);
//declare and
//instantiate yourClock
Search WWH ::
Custom Search