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

                528 Chapter 13 Inheritance and Polymorphism
Now let’s work on implementation of that printPay method in the Employee class. In Figure 13.10 note how printPay prints the date and the employee’s name and then calls getPay. The getPay method is supposed to calculate an employee’s pay. But the Employee class’s getPay method simply returns 0.0. What’s up with that? Are employees really paid nothing? Certainly not! The Employee class’s getPay method is simply a dummy method that’s never executed. The “real” getPay methods (i.e., the ones that are executed) are the overriding definitions in the Salaried and Hourly subclasses. These overriding definitions make the getPay method polymorphic! How does the JVM know to use those methods and not the dummy method in the Employee class? When it performs dynamic binding, the JVM looks at the method’s calling object. For the getPay case, the calling object is an instance of either the Salaried class or the Hourly class. Can you see why?
 /************************************************
*
Employee.java
Dean & Dean
This is a generic description of an employee.
************************************************/
*
*
*
public class Employee
{
}
// end class Employee
private String name;
         Apago PDF Enhancer
public Employee(String name)
//*********************************************
{
}
this.name = name;
//*********************************************
public void printPay(int date)
{
System.out.printf("%2d %10s: %8.2f\n",
date, name, getPay());
} // end printPay
//*********************************************
// This dummy method satisfies the compiler.
public double getPay()
{
}
System.out.println("error! in dummy");
return 0.0;
// end getPay
Figure 13.10
Employee class





























































   560   561   562   563   564