Java Reference
In-Depth Information
We can avoid these types of situations by creating a single heterogeneous
collection that contains all the employees of the company, no matter how the
employee is paid. The Employee class is a common parent, so we can create an
array of Employee references by polymorphism:
Employee [] company = new Employee[200];
The company array consists of 200 Employee references, and each reference
can refer to either a Salary, Hourly, or Contractor object. If a new child class of
Employee comes along in the future, these objects can appear in the company
array as well.
The MyCompany program uses the Employee class and instantiates 200
employees of random pay types, storing them in a single heterogeneous
collection:
public class MyCompany
{
public static void main(String [] args)
{
Employee [] company = new Employee[200];
System.out.println(“Randomly fill the array with employees”);
for(int i = 0; i < company.length; i++)
{
int random = (int) (Math.random() * 3);
if(random == 0)
{
company[i] = new Salary(“Salary “ + i,
“New York, NY”, i, 50000.00);
}
else if(random == 1)
{
company[i] = new Hourly(“Hourly “ + i,
“Chicago, IL”, i, 10.00);
((Hourly) company[i]).setHoursWorked(40);
}
else
{
company[i] = new Contractor(“Contractor “ + i,
“Denver, CO”, i, 200.00);
Search WWH ::




Custom Search