Page 560 - Introduction to Programming with Java: A Problem Solving Approach
P. 560

                526 Chapter 13 Inheritance and Polymorphism
 /*************************************************************
*
Payroll.java
Dean & Dean
This class hires and pays employees.
*************************************************************/
*
*
*
public class Payroll
{
public static void main(String[] args)
{
Employee[] employees = new Employee[100];
Hourly hourly;
employees[0] =
new Hourly("Anna", 25.0);
new Salaried("Simon", 48000);
new Hourly("Donovan", 20.0);
// This arbitrarily assumes that the payroll's month
employees[1] =
employees[2] =
// starts on a Tuesday (day = 2), and it contains 30 days.
for (int date=1,day=2; date<=15; date++,day++,day%=7)
{
for (int i=0;
i<employees.length && employees[i] != null; i++)
       Apago PDF Enhancer
  {
 if (day > 0 && day < 6
&& employees[i] instanceof Hourly)
hourly = (Hourly) employees[i];
hourly.addHours(8);
This selects appropriate elements.
  }
// end class Payroll
}
// end main
{
 }
if ((day == 5 && employees[i] instanceof Hourly) || ⎫ ⎪
(date%15 == 0 && employees[i] instanceof Salaried))⎬ {⎪
 employees[i].printPay(date); ⎭ // end for i
}
This casts elements into their native class.
  }
} // end for date
This selects the appropriate time to print each different type.
Figure 13.9 Driver for simple Payroll program
of the Employee class itself. Even though there may be no instances of the array’s class in the array, the array’s type is the right type to use because it is able to accommodate instances of all classes descended from the array’s class.
Continuing with the main method, the outer for loop steps through 30 days, keeping track of two variables. Notice how the first compartment in the for loop header declares more than one variable of the specified type. The date variable represents the date of the month. It determines when salaried employees















































   558   559   560   561   562