Case Study: Payroll System Using Polymorphism
Case Study Payroll System Using Polymorphism
This section reexamines the CommissionEmployee-BasePlusCommissionEmployee hierarchy that we explored throughout Section 9.4. Now we use an abstract method and polymorphism to perform payroll calculations based on the type of employee. We create an enhanced employee hierarchy to solve the following problem:
A company pays its employees on a weekly basis. The employees are of four types: Salaried employees are paid a fixed weekly salary regardless of the number of hours worked, hourly employees are paid by the hour and receive overtime pay for all hours worked in excess of 40 hours, commission employees are paid a percentage of their sales and salaried-commission employees receive a base salary plus a percentage of their sales. For the current pay period, the company has decided to reward salaried-commission employees by adding 10% to their base salaries. The company wants to implement a Java application that performs its payroll calculations polymorphically.
We use abstract class Employee to represent the general concept of an employee. The classes that extend Employee are SalariedEmployee, CommissionEmployee and HourlyEmployee. Class BasePlusCommissionEmployeewhich extends CommissionEmployeerepresents the last employee type. The UML class diagram in Fig. 10.2 shows the inheritance hierarchy for our polymorphic employee-payroll application. Note that abstract class Employee is italicized, as per the convention of the UML.
Figure 10.2. Employee hierarchy UML class diagram.
Abstract superclass Employee declares the "interface" to the hierarchythat is, the set of methods that a program can invoke on all Employee objects. We use the term "interface" here in a general sense to refer to the various ways programs can communicate with objects of any Employee subclass. Be careful not to confuse the general notion of an "interface" to something with the formal notion of a Java interface, the subject of Section 10.7. Each employee, regardless of the way his or her earnings are calculated, has a first name, a last name and a social security number, so private instance variables firstName, lastName and socialSecurityNumber appear in abstract superclass Employee.
Software Engineering Observation 10.4
A subclass can inherit "interface" or "implementation" from a superclass. Hierarchies designed for implementation inheritance tend to have their functionality high in the hierarchyeach new subclass inherits one or more methods that were implemented in a superclass, and the subclass uses the superclass implementations. Hierarchies designed for interface inheritance tend to have their functionality lower in the hierarchya superclass specifies one or more abstract methods that must be declared for each concrete class in the hierarchy, and the individual subclasses override these methods to provide subclass-specific implementations. |
The following sections implement the Employee class hierarchy. The first four sections each implement one of the concrete classes. The last section implements a test program that builds objects of all these classes and processes those objects polymorphically.
10.5.1. Creating Abstract Superclass Employee
Class Employee (Fig. 10.4) provides methods earnings and toString, in addition to the get and set methods that manipulate Employee's instance variables. An earnings method certainly applies generically to all employees. But each earnings calculation depends on the employee's class. So we declare earnings as abstract in superclass Employee because a default implementation does not make sense for that methodthere is not enough information to determine what amount earnings should return. Each subclass overrides earnings with an appropriate implementation. To calculate an employee's earnings, the program assigns a reference to the employee's object to a superclass Employee variable, then invokes the earnings method on that variable. We maintain an array of Employee variables, each of which holds a reference to an Employee object (of course, there cannot be Employee objects because Employee is an abstract classbecause of inheritance, however, all objects of all subclasses of Employee may nevertheless be thought of as Employee objects). The program iterates through the array and calls method earnings for each Employee object. Java processes these method calls polymorphically. Including earnings as an abstract method in Employee forces every direct subclass of Employee to override earnings in order to become a concrete class. This enables the designer of the class hierarchy to demand that each subclass provide an appropriate pay calculation.
Method toString in class Employee returns a String containing the first name, last name and social security number of the employee. As we will see, each subclass of Employee overrides method toString to create a string representation of an object of that class that contains the employee's type (e.g., "salaried employee:") followed by the rest of the employee's information.
The diagram in Fig. 10.3 shows each of the five classes in the hierarchy down the left side and methods earnings and toString across the top. For each class, the diagram shows the desired results of each method. [Note: We do not list superclass Employee's get and set methods because they are not overridden in any of the subclasseseach of these methods is inherited and used "as is" by each of the subclasses.]
Figure 10.3. Polymorphic interface for the Employee hierarchy classes.
Let us consider class Employee's declaration (Fig. 10.4). The class includes a constructor that takes the first name, last name and social security number as arguments (lines 1116); get methods that return the first name, last name and social security number (lines 2528, 3740 and 4952, respectively); set methods that set the first name, last name and social security number (lines 1922, 3134 and 4346, respectively); method toString (lines 5559), which returns the string representation of Employee; and abstract method earnings (line 62), which will be implemented by subclasses. Note that the Employee constructor does not validate the social security number in this example. Normally, such validation should be provided.
Figure 10.4. Employee abstract superclass.
(This item is displayed on pages 471 - 472 in the print version)
1 // Fig. 10.4: Employee.java 2 // Employee abstract superclass. 3 4 public abstract class Employee 5 { 6 private String firstName; 7 private String lastName; 8 private String socialSecurityNumber; 9 10 // three-argument constructor 11 public Employee( String first, String last, String ssn ) 12 { 13 firstName = first; 14 lastName = last; 15 socialSecurityNumber = ssn; 16 } // end three-argument Employee constructor 17 18 // set first name 19 public void setFirstName( String first ) 20 { 21 firstName = first; 22 } // end method setFirstName 23 24 // return first name 25 public String getFirstName() 26 { 27 return firstName; 28 } // end method getFirstName 29 30 // set last name 31 public void setLastName( String last ) 32 { 33 lastName = last; 34 } // end method setLastName 35 36 // return last name 37 public String getLastName() 38 { 39 return lastName; 40 } // end method getLastName 41 42 // set social security number 43 public void setSocialSecurityNumber( String ssn ) 44 { 45 socialSecurityNumber = ssn; // should validate 46 } // end method setSocialSecurityNumber 47 48 // return social security number 49 public String getSocialSecurityNumber() 50 { 51 return socialSecurityNumber; 52 } // end method getSocialSecurityNumber 53 54 // return String representation of Employee object 55 public String toString() 56 { 57 return String.format( "%s %s social security number: %s", 58 getFirstName(), getLastName(), getSocialSecurityNumber() ); 59 } // end method toString 60 61 // abstract method overridden by subclasses 62 public abstract double earnings(); // no implementation here 63 } // end abstract class Employee |
Why did we decide to declare earnings as an abstract method? It simply does not make sense to provide an implementation of this method in class Employee. We cannot calculate the earnings for a general Employeewe first must know the specific Employee type to determine the appropriate earnings calculation. By declaring this method abstract, we indicate that each concrete subclass must provide an appropriate earnings implementation and that a program will be able to use superclass Employee variables to invoke method earnings polymorphically for any type of Employee.
10.5.2. Creating Concrete Subclass SalariedEmployee
Class SalariedEmployee (Fig. 10.5) extends class Employee (line 4) and overrides earnings (lines 2932), which makes SalariedEmployee a concrete class. The class includes a constructor (lines 914) that takes a first name, a last name, a social security number and a weekly salary as arguments; a set method to assign a new non-negative value to instance variable weeklySalary (lines 1720); a get method to return weeklySalary's value (lines 2326); a method earnings (lines 2932) to calculate a SalariedEmployee's earnings; and a method toString (lines 3539), which returns a String including the employee's type, namely, "salaried employee:" followed by employee-specific information produced by superclass Employee's toString method and SalariedEmployee's getWeeklySalary method. Class SalariedEmployee's constructor passes the first name, last name and social security number to the Employee constructor (line 12) to initialize the private instance variables not inherited from the superclass. Method earnings overrides abstract method earnings in Employee to provide a concrete implementation that returns the SalariedEmployee's weekly salary. If we do not implement earnings, class SalariedEmployee must be declared abstractotherwise, a compilation error occurs (and, of course, we want SalariedEmployee here to be a concrete class).
Figure 10.5. SalariedEmployee class derived from Employee.
(This item is displayed on pages 472 - 473 in the print version)
1 // Fig. 10.5: SalariedEmployee.java 2 // SalariedEmployee class extends Employee. 3 4 public class SalariedEmployee extends Employee 5 { 6 private double weeklySalary; 7 8 // four-argument constructor 9 public SalariedEmployee( String first, String last, String ssn, 10 double salary ) 11 { 12 super( first, last, ssn ); // pass to Employee constructor 13 setWeeklySalary( salary ); // validate and store salary 14 } // end four-argument SalariedEmployee constructor 15 16 // set salary 17 public void setWeeklySalary( double salary ) 18 { 19 weeklySalary = salary < 0.0 ? 0.0 : salary; 20 } // end method setWeeklySalary 21 22 // return salary 23 public double getWeeklySalary() 24 { 25 return weeklySalary; 26 } // end method getWeeklySalary 27 28 // calculate earnings; override abstract method earnings in Employee 29 public double earnings() 30 { 31 return getWeeklySalary(); 32 } // end method earnings 33 34 // return String representation of SalariedEmployee object 35 public String toString() 36 { 37 return String.format( "salaried employee: %s %s: $%,.2f", 38 super.toString(), "weekly salary", getWeeklySalary() ); 39 } // end method toString 40 } // end class SalariedEmployee |
Method toString (lines 3539) of class SalariedEmployee overrides Employee method toString. If class SalariedEmployee did not override toString, SalariedEmployee would have inherited the Employee version of toString. In that case, SalariedEmployee's toString method would simply return the employee's full name and social security number, which does not adequately represent a SalariedEmployee. To produce a complete string representation of a SalariedEmployee, the subclass's toString method returns "salaried employee:" followed by the superclass Employee-specific information (i.e., first name, last name and social security number) obtained by invoking the superclass's toString (line 38)this is a nice example of code reuse. The string representation of a SalariedEmployee also contains the employee's weekly salary obtained by invoking the class's getWeeklySalary method.
10.5.3. Creating Concrete Subclass HourlyEmployee
Class HourlyEmployee (Fig. 10.6) also extends class Employee (line 4). The class includes a constructor (lines 1016) that takes as arguments a first name, a last name, a social security number, an hourly wage and the number of hours worked. Lines 1922 and 3135 declare set methods that assign new values to instance variables wage and hours, respectively. Method setWage (lines 1922) ensures that wage is non-negative, and method setHours (lines 3135) ensures that hours is between 0 and 168 (the total number of hours in a week). Class HourlyEmployee also includes get methods (lines 2528 and 3841) to return the values of wage and hours, respectively; a method earnings (lines 4450) to calculate an HourlyEmployee's earnings; and a method toString (lines 5358), which returns the employee's type, namely, "hourly employee:" and employee-specific information. Note that the HourlyEmployee constructor, like the SalariedEmployee constructor, passes the first name, last name and social security number to the superclass Employee constructor (line 13) to initialize the private instance variables. In addition, method toString calls superclass method toString (line 56) to obtain the Employee-specific information (i.e., first name, last name and social security number)this is another nice example of code reuse.
Figure 10.6. HourlyEmployee class derived from Employee.
(This item is displayed on pages 474 - 475 in the print version)
1 // Fig. 10.6: HourlyEmployee.java 2 // HourlyEmployee class extends Employee. 3 4 public class HourlyEmployee extends Employee 5 { 6 private double wage; // wage per hour 7 private double hours; // hours worked for week 8 9 // five-argument constructor 10 public HourlyEmployee( String first, String last, String ssn, 11 double hourlyWage, double hoursWorked ) 12 { 13 super( first, last, ssn ); 14 setWage( hourlyWage ); // validate hourly wage 15 setHours( hoursWorked ); // validate hours worked 16 } // end five-argument HourlyEmployee constructor 17 18 // set wage 19 public void setWage( double hourlyWage ) 20 { 21 wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage; 22 } // end method setWage 23 24 // return wage 25 public double getWage() 26 { 27 return wage; 28 } // end method getWage 29 30 // set hours worked 31 public void setHours( double hoursWorked ) 32 { 33 hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ? 34 hoursWorked : 0.0; 35 } // end method setHours 36 37 // return hours worked 38 public double getHours() 39 { 40 return hours; 41 } // end method getHours 42 43 // calculate earnings; override abstract method earnings in Employee 44 public double earnings() 45 { 46 if ( getHours() <= 40 ) // no overtime 47 return getWage() * getHours(); 48 else 49 return 40 * getWage() + ( gethours() - 40 ) * getWage() * 1.5; 50 } // end method earnings 51 52 // return String representation of HourlyEmployee object 53 public String toString() 54 { 55 return String.format( "hourly employee: %s %s: $%,.2f; %s: %,.2f", 56 super.toString(), "hourly wage", getWage(), 57 "hours worked", getHours() ); 58 } // end method toString 59 } // end class HourlyEmployee |
10.5.4. Creating Concrete Subclass CommissionEmployee
Class CommissionEmployee (Fig. 10.7) extends class Employee (line 4). The class includes a constructor (lines 1016) that takes a first name, a last name, a social security number, a sales amount and a commission rate; set methods (lines 1922 and 3134) to assign new values to instance variables commissionRate and grossSales, respectively; get methods (lines 2528 and 3740) that retrieve the values of these instance variables; method earnings (lines 4346) to calculate a CommissionEmployee's earnings; and method toString (lines 4955), which returns the employee's type, namely, "commission employee:" and employee-specific information. The CommissionEmployee's constructor also passes the first name, last name and social security number to the Employee constructor (line 13) to initialize Employee's private instance variables. Method toString calls superclass method toString (line 52) to obtain the Employee-specific information (i.e., first name, last name and social security number).
Figure 10.7. CommissionEmployee class derived from Employee.
(This item is displayed on pages 475 - 476 in the print version)
1 // Fig. 10.7: CommissionEmployee.java 2 // CommissionEmployee class extends Employee. 3 4 public class CommissionEmployee extends Employee 5 { 6 private double grossSales; // gross weekly sales 7 private double commissionRate; // commission percentage 8 9 // five-argument constructor 10 public CommissionEmployee( String first, String last, String ssn, 11 double sales, double rate ) 12 { 13 super( first, last, ssn ); 14 setGrossSales( sales ); 15 setCommissionRate( rate ); 16 } // end five-argument CommissionEmployee constructor 17 18 // set commission rate 19 public void setCommissionRate( double rate ) 20 { 21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0; 22 } // end method setCommissionRate 23 24 // return commission rate 25 public double getCommissionRate() 26 { 27 return commissionRate; 28 } // end method getCommissionRate 29 30 // set gross sales amount 31 public void setGrossSales( double sales ) 32 { 33 grossSales = ( sales < 0.0 ) ? 0.0 : sales; 34 } // end method setGrossSales 35 36 // return gross sales amount 37 public double getGrossSales() 38 { 39 return grossSales; 40 } // end method getGrossSales 41 42 // calculate earnings; override abstract method earnings in Employee 43 public double earnings() 44 { 45 return getCommissionRate() * getGrossSales(); 46 } // end method earnings 47 48 // return String representation of CommissionEmployee object 49 public String toString() 50 { 51 return String.format( "%s: %s %s: $%,.2f; %s: %.2f", 52 "commission employee", super.toString(), 53 "gross sales", getGrossSales(), 54 "commission rate", getCommissionRate() ); 55 } // end method toString 56 } // end class CommissionEmployee |
10.5.5. Creating Indirect Concrete Subclass BasePlusCommissionEmployee
Class BasePlusCommissionEmployee (Fig. 10.8) extends class CommissionEmployee (line 4) and therefore is an indirect subclass of class Employee. Class BasePlusCommissionEmployee has a constructor (lines 914) that takes as arguments a first name, a last name, a social security number, a sales amount, a commission rate and a base salary. It then passes the first name, last name, social security number, sales amount and commission rate to the CommissionEmployee constructor (line 12) to initialize the inherited members. BasePlusCommissionEmployee also contains a set method (lines 1720) to assign a new value to instance variable baseSalary and a get method (lines 2326) to return baseSalary's value. Method earnings (lines 2932) calculates a BasePlusCommissionEmployee's earnings. Note that line 31 in method earnings calls superclass CommissionEmployee's earnings method to calculate the commission-based portion of the employee's earnings. This is a nice example of code reuse. BasePlusCommissionEmployee's toString method (lines 3540) creates a string representation of a BasePlusCommissionEmployee that contains "base-salaried", followed by the String obtained by invoking superclass CommissionEmployee's toString method (another example of code reuse), then the base salary. The result is a String beginning with "base-salaried commission employee" followed by the rest of the BasePlusCommissionEmployee's information. Recall that CommissionEmployee's toString obtains the employee's first name, last name and social security number by invoking the toString method of its superclass (i.e., Employee)yet another example of code reuse. Note that BasePlusCommissionEmployee's toString initiates a chain of method calls that span all three levels of the Employee hierarchy.
Figure 10.8. BasePlusCommissionEmployee class derived from CommissionEmployee.
(This item is displayed on page 477 in the print version)
1 // Fig. 10.8: BasePlusCommissionEmployee.java 2 // BasePlusCommissionEmployee class extends CommissionEmployee. 3 4 public class BasePlusCommissionEmployee extends CommissionEmployee 5 { 6 private double baseSalary; // base salary per week 7 8 // six-argument constructor 9 public BasePlusCommissionEmployee( String first, String last, 10 String ssn, double sales, double rate, double salary ) 11 { 12 super( first, last, ssn, sales, rate ); 13 setBaseSalary( salary ); // validate and store base salary 14 } // end six-argument BasePlusCommissionEmployee constructor 15 16 // set base salary 17 public void setBaseSalary( double salary ) 18 { 19 baseSalary = ( salary < 0.0 ) ? 0.0 : salary; // non-negative 20 } // end method setBaseSalary 21 22 // return base salary 23 public double getBaseSalary() 24 { 25 return baseSalary; 26 } // end method getBaseSalary 27 28 // calculate earnings; override method earnings in CommissionEmployee 29 public double earnings() 30 { 31 return getBaseSalary() + super.earnings(); 32 } // end method earnings 33 34 // return String representation of BasePlusCommissionEmployee object 35 public String toString() 36 { 37 return String.format( "%s %s; %s: $%,.2f", 38 "base-salaried", super.toString(), 39 "base salary", getBaseSalary() ); 40 } // end method toString 41 } // end class BasePlusCommissionEmployee |
10.5.6. Demonstrating Polymorphic Processing, Operator instanceof and Downcasting
To test our Employee hierarchy, the application in Fig. 10.9 creates an object of each of the four concrete classes SalariedEmployee, HourlyEmployee, CommissionEmployee and BasePlusCommissionEmployee. The program manipulates these objects, first via variables of each object's own type, then polymorphically, using an array of Employee variables. While processing the objects polymorphically, the program increases the base salary of each BasePlusCommissionEmployee by 10% (this, of course, requires determining the object's type at execution time). Finally, the program polymorphically determines and outputs the type of each object in the Employee array. Lines 918 create objects of each of the four concrete Employee subclasses. Lines 2230 output the string representation and earnings of each of these objects. Note that each object's toString method is called implicitly by printf when the object is output as a String with the %s format specifier.
Figure 10.9. Employee class hierarchy test program.
(This item is displayed on pages 478 - 480 in the print version)
1 // Fig. 10.9: PayrollSystemTest.java 2 // Employee hierarchy test program. 3 4 public class PayrollSystemTest 5 { 6 public static void main( String args[] ) 7 { 8 // create subclass objects 9 SalariedEmployee salariedEmployee = 10 new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 ); 11 HourlyEmployee hourlyEmployee = 12 new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 ); 13 CommissionEmployee commissionEmployee = 14 new CommissionEmployee( 15 "Sue", "Jones", "333-33-3333", 10000, .06 ); 16 BasePlusCommissionEmployee basePlusCommissionEmployee = 17 new BasePlusCommissionEmployee( 18 "Bob", "Lewis", "444-44-4444", 5000, .04, 300 ); 19 20 System.out.println( "Employees processed individually: " ); 21 22 System.out.printf( "%s %s: $%,.2f ", 23 salariedEmployee, "earned", salariedEmployee.earnings() ); 24 System.out.printf( "%s %s: $%,.2f ", 25 hourlyEmployee, "earned", hourlyEmployee.earnings() ); 26 System.out.printf( "%s %s: $%,.2f ", 27 commissionEmployee, "earned", commissionEmployee.earnings() ); 28 System.out.printf( "%s %s: $%,.2f ", 29 basePlusCommissionEmployee, 30 "earned", basePlusCommissionEmployee.earnings() ); 31 32 // create four-element Employee array 33 Employee employees[] = new Employee[ 4 ]; 34 35 // initialize array with Employees 36 employees[ 0 ] = salariedEmployee; 37 employees[ 1 ] = hourlyEmployee; 38 employees[ 2 ] = commissionEmployee; 39 employees[ 3 ] = basePlusCommissionEmployee; 40 41 System.out.println( "Employees processed polymorphically: " ); 42 43 // generically process each element in array employees 44 for ( Employee currentEmployee : employees ) 45 { 46 System.out.println( currentEmployee ); // invokes toString 47 48 // determine whether element is a BasePlusCommissionEmployee 49 if ( currentEmployee instanceof BasePlusCommissionEmployee ) 50 { 51 // downcast Employee reference to 52 // BasePlusCommissionEmployee reference 53 BasePlusCommissionEmployee employee = 54 ( BasePlusCommissionEmployee ) currentEmployee; 55 56 double oldBaseSalary = employee.getBaseSalary(); 57 employee.setBaseSalary( 1.10 * oldBaseSalary ); 58 System.out.printf( 59 "new base salary with 10%% increase is: $%,.2f ", 60 employee.getBaseSalary() ); 61 } // end if 62 63 System.out.printf( 64 "earned $%,.2f ", currentEmployee.earnings() ); 65 } // end for 66 67 // get type name of each object in employees array 68 for ( int j = 0; j < employees.length; j++ ) 69 System.out.printf( "Employee %d is a %s ", j, 70 employees[ j ].getClass().getName() ); 71 } // end main 72 } // end class PayrollSystemTest
|
Line 33 declares employees and assigns it an array of four Employee variables. Line 36 assigns to element employees[ 0 ] the reference to a SalariedEmployee object. Line 37 assigns to element employees[ 1 ] the reference to an HourlyEmployee object. Line 38 assigns to element employees[ 2 ] the reference to a CommissionEmployee object. Line 39 assigns to element employee[ 3 ] the reference to a BasePlusCommissionEmployee object. Each assignment is allowed, because a SalariedEmployee is an Employee, an HourlyEmployee is an Employee, a CommissionEmployee is an Employee and a BasePlusCommissionEmployee is an Employee. Therefore, we can assign the references of SalariedEmployee, HourlyEmployee, CommissionEmployee and BasePlusCommissionEmployee objects to superclass Employee variables, even though Employee is an abstract class.
Lines 4465 iterate through array employees and invoke methods toString and earnings with Employee variable currentEmployee, which is assigned the reference to a different Employee in the array during each iteration. The output illustrates that the appropriate methods for each class are indeed invoked. All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers. This process is known as dynamic binding or late binding. For example, line 46 implicitly invokes method toString of the object to which currentEmployee refers. As a result of dynamic binding, Java decides which class's toString method to call at execution time rather than at compile time. Please note that only the methods of class Employee can be called via an Employee variable (and Employee, of course, includes the methods of class Object). (Section 9.7 discusses the set of methods that all classes inherit from class Object.) A superclass reference can be used to invoke only methods of the superclass.
We perform special processing on BasePlusCommissionEmployee objectsas we encounter these objects, we increase their base salary by 10%. When processing objects polymorphically, we typically do not need to worry about the "specifics," but to adjust the base salary, we do have to determine the specific type of Employee object at execution time. Line 49 uses the instanceof operator to determine whether a particular Employee object's type is BasePlusCommissionEmployee. The condition in line 49 is true if the object referenced by currentEmployee is a BasePlusCommissionEmployee. This would also be true for any object of a BasePlusCommissionEmployee subclass because of the is-a relationship a subclass has with its superclass. Lines 5354 downcast currentEmployee from type Employee to type BasePlusCommissionEmployeethis cast is allowed only if the object has an is-a relationship with BasePlusCommissionEmployee. The condition at line 49 ensures that this is the case. This cast is required if we are to invoke subclass BasePlusCommissionEmployee methods getBaseSalary and setBaseSalary on the current Employee objectas you will see momentarily, attempting to invoke a subclass-only method directly on a superclass reference is a compilation error.
Common Programming Error 10.3
Assigning a superclass variable to a subclass variable (without an explicit cast) is a compilation error. |
Software Engineering Observation 10.5
If at execution time the reference of a subclass object has been assigned to a variable of one of its direct or indirect superclasses, it is acceptable to cast the reference stored in that superclass variable back to a reference of the subclass type. Before performing such a cast, use the instanceof operator to ensure that the object is indeed an object of an appropriate subclass type. |
Common Programming Error 10.4
When downcasting an object, a ClassCastException occurs, if at execution time the object does not have an is-a relationship with the type specified in the cast operator. An object can be cast only to its own type or to the type of one of its superclasses. |
If the instanceof expression in line 49 is TRue, the if statement (lines 4961) performs the special processing required for the BasePlusCommissionEmployee object. Using BasePlusCommissionEmployee variable employee, lines 56 and 57 invoke subclass-only methods getBaseSalary and setBaseSalary to retrieve and update the employee's base salary with the 10% raise.
Lines 6364 invoke method earnings on currentEmployee, which calls the appropriate subclass object's earnings method polymorphically. Note that obtaining the earnings of the SalariedEmployee, HourlyEmployee and CommissionEmployee polymorphically in lines 6364 produces the same result as obtaining these employees' earnings individually in lines 2227. However, the earnings amount obtained for the BasePlusCommissionEmployee in lines 6364 is higher than that obtained in lines 2830, due to the 10% increase in its base salary.
Lines 6870 display each employee's type as a string. Every object in Java knows its own class and can access this information through method getClass, which all classes inherit from class Object. Method getClass returns an object of type Class (package java.lang), which contains information about the object's type, including its class name. Line 70 invokes method getClass on the object to get its runtime class (i.e., a Class object that represents the object's type). Then method getName is invoked on the object returned by getClass to get the class's name.
In the previous example, we avoid several compilation errors by downcasting an Employee variable to a BasePlusCommissionEmployee variable in lines 5354. If we remove the cast operator ( BasePlusCommissionEmployee ) from line 54 and attempt to assign Employee variable currentEmployee directly to BasePlusCommissionEmployee variable employee, we would receive an "incompatible types" compilation error. This error indicates that the attempt to assign the reference of superclass object commissionEmployee to subclass variable basePlusCommissionEmployee is not allowed. The compiler prevents this assignment because a CommissionEmployee is not a BasePlusCommissionEmployeethe is-a relationship applies only between the subclass and its superclasses, not vice versa.
Similarly, if lines 56, 57 and 60 used superclass variable currentEmployee, rather than subclass variable employee, to invoke subclass-only methods getBaseSalary and setBaseSalary, we would receive a "cannot find symbol" compilation error on each of these lines. Attempting to invoke subclass-only methods on a superclass reference is not allowed. While lines 56, 57 and 60 execute only if instanceof in line 49 returns true to indicate that currentEmployee has been assigned a reference to a BasePlusCommissionEmployee object, we cannot attempt to invoke subclass BasePlusCommissionEmployee methods getBaseSalary and setBaseSalary on superclass Employee reference currentEmployee. The compiler would generate errors on lines 56, 57 and 60, because getBaseSalary and setBaseSalary are not superclass methods and cannot be invoked on a superclass variable. Although the actual method that is called depends on the object's type at execution time, a variable can be used to invoke only those methods that are members of that variable's type, which the compiler verifies. Using a superclass Employee variable, we can invoke only methods found in class Employeeearnings, toString and Employee's get and set methods.
10.5.7. Summary of the Allowed Assignments Between Superclass and Subclass Variables
Now that you have seen a complete application that processes diverse subclass objects polymorphically, we summarize what you can and cannot do with superclass and subclass objects and variables. Although a subclass object also is a superclass object, the two objects are nevertheless different. As discussed previously, subclass objects can be treated as if they are superclass objects. However, the subclass can have additional subclass-only members. For this reason, assigning a superclass reference to a subclass variable is not allowed without an explicit castsuch an assignment would leave the subclass members undefined for the superclass object.
In the current section, in Section 10.3 and in Chapter 9, we have discussed four ways to assign superclass and subclass references to variables of superclass and subclass types:
- Assigning a superclass reference to a superclass variable is straightforward.
- Assigning a subclass reference to a subclass variable is straightforward.
- Assigning a subclass reference to a superclass variable is safe, because the subclass object is an object of its superclass. However, this reference can be used to refer only to superclass members. If this code refers to subclass-only members through the superclass variable, the compiler reports errors.
- Attempting to assign a superclass reference to a subclass variable is a compilation error. To avoid this error, the superclass reference must be cast to a subclass type explicitly. At execution time, if the object to which the reference refers is not a subclass object, an exception will occur. (For more on exception handling, see Chapter 13, Exception Handling.) The instanceof operator can be used to ensure that such a cast is performed only if the object is a subclass object.