Java Reference
In-Depth Information
Figure 9.4
Output of the DoubleArray program.
Example of a Heterogeneous Collection
I promised in Chapter 8, “Polymorphism and Abstraction,” that I would show
you how to create a heterogeneous collection of Employee objects. The abstract
Employee class has three child classes: Salary, Hourly, and Contractor. Sup-
pose that we have a company that never has more than 200 employees. We
could create three different arrays to keep track of the employees:
Salary [] salaries = new Salary[200];
Hourly [] hourlies = new Hourly[200];
Contractor [] contractors = new Contractor[200];
Using three different arrays has its disadvantages. First of all, using 200 ref-
erences of each type is a waste of memory. But how do we distribute the
employee types? What if one year we have 100 salaried, 100 hourly, and no
contract employees, but a year later we have 150 salaried, 25 hourly, and 25
contract employees? I suppose we could start out with smaller arrays, but if
any one of three arrays was too small, a larger array would have to be instan-
tiated and the data from the smaller array copied into the larger array.
The second disadvantage has to do with changes to our program in the
future. What if a new type of Employee is added? Then, a new array is needed,
and the question about how big it should be arises again.
Search WWH ::




Custom Search