Java Reference
In-Depth Information
This section discusses, in general, how to create and work with an array of objects.
Suppose that you have 100 employees who are paid on an hourly basis, and you need to
keep track of their arrival and departure times. In Chapter 8, we designed and imple-
mented the
class
Clock
to implement the time of day in a program. You can declare
two arrays—
arrivalTimeEmp
and
departureTimeEmp
—of 100 elements each,
wherein each element is a reference variable of
Clock
type. Consider the following
statement:
Clock[] arrivalTimeEmp =
new
Clock[100];
//Line 1
The statement in Line 1 creates the array shown in Figure 9-12.
arrivalTimeEmp
arrivalTimeEmp[0]
.
.
.
arrivalTimeEmp[49]
.
.
.
arrivalTimeEmp[99]
FIGURE 9-12
Array
arrivalTimeEmp
The statement in Line 1 creates only the array, not the objects
arrivalTimeEmp[0]
,
arrivalTimeEmp[1]
,...,
arrivalTimeEmp[99]
. We still need to instantiate
Clock
objects for each array element. Consider the following statements:
for
(
int
j = 0; j < arrivalTimeEmp.length; j++)
//Line 2
arrivalTimeEmp[j] =
new
Clock();
//Line 3
The statements in Lines 2 and 3 instantiate the objects
arrivalTimeEmp[0]
,
arrivalTimeEmp[1]
,...,
arrivalTimeEmp[99]
, as shown in Figure 9-13.
Search WWH ::
Custom Search