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

                Go back to Figure 13.9’s main method and note the assignment of an Hourly object into employees[0].Whenemployees[i].printPay()getscalledwithi equalto0,thecallingobject is an Hourly object. Within the printPay method, when getPay is called, the calling object is still an Hourly object. Therefore, the JVM uses the Hourly class’s getPay method. And that’s what we want— the employees[0] object is an Hourly, so it uses the Hourly class’s getPay method. The same argu- ment can be applied to the employees[1] object. Since it’s a Salaried object, it uses the Salaried class’s getPay method. Thanks to polymorphism and dynamic binding, life is good.
The really cool thing about polymorphism and dynamic binding is being able to program generically. In the main method, we can call printPay for all the objects in the array and not worry about whether the object is an Hourly or a Salaried. We just assume that printPay works appropriately for each employee. This ability to program generically enables programmers to think about the big picture without getting bogged down in details.
In the Employee class, were you bothered by the dummy getPay method? Were you thinking “Why include a getPay method in the Employee class even though it’s never executed?” It’s needed because if there were no getPay method in the Employee class, the compiler would generate an error. Why? Because when the compiler sees a method call with no dot prefix, it checks to make sure that the method can be found within the current class. The getPay() method call (within the printPay method) has no dot prefix, so the compiler requires the Employee class to have a getPay method.
Now it’s time to implement the “real” getPay methods. See Figures 13.11 and 13.12. The methods
13.7 Polymorphism with Arrays 529
 /**********************************************
Salaried.javaApago PDF Enhancer Dean & Dean
This class implements a salaried employee.
**********************************************/
*
*
*
*
public class Salaried extends Employee
{
}
// end class Salaried
private double salary;
// per year
//*******************************************
public Salaried(String name, double salary)
{
super(name);
this.salary = salary;
} // end constructor
//*******************************************
public double getPay()
{
return this.salary / 24; // per half month
} // end getPay
Figure 13.11
Salaried class



































































   561   562   563   564   565