Anda di halaman 1dari 35

10

One Ring to rule them all,


One Ring to nd them,
One Ring to bring them all
and in the darkness bind
them.

Object-Oriented
Programming:
Polymorphism

John Ronald Reuel Tolkien

General propositions do not


decide concrete cases.
Oliver Wendell Holmes

A philosopher of imposing
stature doesnt think in a
vacuum. Even his most
abstract ideas are, to some
extent, conditioned by
what is or is not known
in the time when he lives.
Alfred North Whitehead

Why art thou cast down,


O my soul?
Psalms 42:5

OBJECTIVES
In this chapter you will learn:

The concept of polymorphism.

To use overridden methods to effect polymorphism.

To distinguish between abstract and concrete classes.

To declare abstract methods to create abstract classes.

How polymorphism makes systems extensible and


maintainable.

To determine an objects type at execution time.

To declare and implement interfaces.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Assignment Checklist
Name:

Date:

Section:

Exercises

Assigned: Circle assignments

Prelab Activities
Matching

YES

NO

Fill in the Blank

YES

NO

Short Answer

YES

NO

Programming Output

YES

NO

Correct the Code

YES

NO

YES

NO

Lab Exercises
Exercise 1 Payroll System Modification
Follow-Up Question and Activity

Exercise 2 Accounts Payable System Modification YES


Follow-Up Question and Activity
Debugging

NO

1
YES

NO

Labs Provided by Instructor


1.
2.
3.

Postlab Activities
Coding Exercises

1, 2, 3, 4, 5, 6, 7, 8

Programming Challenges

1, 2

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Date Due

Chapter 10

Object-Oriented Programming: Polymorphism

Prelab Activities
Matching
Name:

Date:

Section:
After reading Chapter 10 of Java How to Program: Sixth Edition, answer the given questions. The questions are
intended to test and reinforce your understanding of key concepts. You may answer the questions before or during the lab.
For each term in the left column, write the letter for the description from the right column that best matches the
term.
Term

Description

1.

abstract

method

2.

getClass

method

3.

implements

keyword

4. type-wrapper classes
5. downcasting
6. concrete class
7. polymorphism
8.

instanceof

9.

final

10.

getName

11.

abstract

12. interface

method
class

a) Can be used in place of an abstract class when there is no default


implementation to inherit.
b) Indicates that a method cannot be overridden or that a class cannot be a superclass.
c)

Class method which returns the name of the class associated with
the Class object.

d) An operator that returns true if its left operand (a variable of a reference type) has the is-a relationship with its right operand (a class
or interface name).
e) Uses superclass references to manipulate sets of subclass objects in
a generic manner.
f)

Casting a superclass reference to a subclass reference.

g) Cannot be instantiated; used primarily for inheritance.


h) Indicates that a class will declare each method in an interface with
the signature specified in the interface declaration.
i)

Must be overridden in a subclass; otherwise, the subclass must be


declared abstract.

j)

Returns an object that can be used to determine information


about the objects class.

k) A class that can be used to create objects.


l)

Classes in the java.lang package that are used to create objects


containing values of primitive types.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Prelab Activities

Name:

Fill in the Blank


Fill in the Blank

Name:

Date:

Section:
Fill in the blanks for each of the following statements:
13. With

, it becomes possible to design and implement systems that are more extensible.

14. Although we cannot instantiate objects of abstract superclasses, we can declare


perclass types.

of abstract su-

15. It is a syntax error if a class with one or more abstract methods is not explicitly declared
16. It is possible to assign a superclass reference to a subclass variable by
type.
17. A(n)

the reference to the subclass

may contain a set of public abstract methods and/or public static final fields.

18. When a method is invoked through a superclass reference to a subclass object, Java executes the version of
the method found in the
.
19. The
operator determines whether the type of the object to which its left operand refers has an isa relationship with the type specified as its right operand.
20. To use an interface, a class must specify that it
the interface and must declare every method in
the interface with the signatures specified in the interface declaration.
21. When a class implements an interface, it establishes an

relationship with the interface type.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Prelab Activities

Name:

Short Answer
Short Answer

Name:

Date:

Section:
In the space provided, answer each of the given questions. Your answers should be as concise as possible; aim for
two or three sentences.
22. Describe the concept of polymorphism.

23. Define what it means to declare a method final and what it means to declare a class final.

24. What happens when a class specifies that it implements an interface, but does not provide declarations of all
the methods in the interface?

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

10

Object-Oriented Programming: Polymorphism

Prelab Activities

Chapter 10

Name:

Short Answer
25. Describe how to determine the class name of an objects class.

26. Distinguish between an abstract class and a concrete class.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Prelab Activities

11

Name:

Programming Output
Programming Output

Name:

Date:

Section:
For each of the given program segments, read the code and write the output in the space provided below each
program. [Note: Do not execute these programs on a computer.]

Use the class definitions in Fig. L 10.1Fig. L 10.3 when answering Programming Output Exercises 2730.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

// Employee.java
// Employee abstract superclass.
public abstract class Employee
{
private String firstName;
private String lastName;
private String socialSecurityNumber;
// three-argument constructor
public Employee( String first, String last, String ssn )
{
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
} // end three-argument Employee constructor
// set first name
public void setFirstName( String first )
{
firstName = first;
} // end method setFirstName
// return first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// set last name
public void setLastName( String last )
{
lastName = last;
} // end method setLastName
// return last name
public String getLastName()
{
return lastName;
} // end method getLastName

Fig. L 10.1 |

Employee

abstract superclass. (Part 1 of 2.)

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

12

Object-Oriented Programming: Polymorphism

Prelab Activities

Chapter 10

Name:

Programming Output

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

// set social security number


public void setSocialSecurityNumber( String ssn )
{
socialSecurityNumber = ssn; // should validate
} // end method setSocialSecurityNumber
// return social security number
public String getSocialSecurityNumber()
{
return socialSecurityNumber;
} // end method getSocialSecurityNumber
// return String representation of Employee object
public String toString()
{
return String.format( "%s %s\nsocial security number: %s",
getFirstName(), getLastName(), getSocialSecurityNumber() );
} // end method toString
// abstract method overridden by subclasses
public abstract double earnings(); // no implementation here
} // end abstract class Employee

Fig. L 10.1 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Employee

abstract superclass. (Part 2 of 2.)

// SalariedEmployee.java
// SalariedEmployee class extends Employee.
public class SalariedEmployee extends Employee
{
private double weeklySalary;
// four-argument constructor
public SalariedEmployee( String first, String last, String ssn,
double salary )
{
super( first, last, ssn ); // pass to Employee constructor
setWeeklySalary( salary ); // validate and store salary
} // end four-argument SalariedEmployee constructor
// set salary
public void setWeeklySalary( double salary )
{
weeklySalary = salary < 0.0 ? 0.0 : salary;
} // end method setWeeklySalary
// return salary
public double getWeeklySalary()
{
return weeklySalary;
} // end method getWeeklySalary
// calculate earnings; override abstract method earnings in Employee
public double earnings()
{

Fig. L 10.2 |

SalariedEmployee

class derived from Employee. (Part 1 of 2.)

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Prelab Activities

Name:

Programming Output

31
32
33
34
35
36
37
38
39
40

return getWeeklySalary();
} // end method earnings
// return String representation of SalariedEmployee object
public String toString()
{
return String.format( "salaried employee: %s\n%s: $%,.2f",
super.toString(), "weekly salary", getWeeklySalary() );
} // end method toString
} // end class SalariedEmployee

Fig. L 10.2 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

SalariedEmployee

class derived from Employee. (Part 2 of 2.)

// CommissionEmployee.java
// CommissionEmployee class extends Employee.
public class CommissionEmployee extends Employee
{
private double grossSales; // gross weekly sales
private double commissionRate; // commission percentage
// five-argument constructor
public CommissionEmployee( String first, String last, String ssn,
double sales, double rate )
{
super( first, last, ssn );
setGrossSales( sales );
setCommissionRate( rate );
} // end five-argument CommissionEmployee constructor
// set commission rate
public void setCommissionRate( double rate )
{
commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
} // end method setCommissionRate
// return commission rate
public double getCommissionRate()
{
return commissionRate;
} // end method getCommissionRate
// set gross sales amount
public void setGrossSales( double sales )
{
grossSales = ( sales < 0.0 ) ? 0.0 : sales;
} // end method setGrossSales
// return gross sales amount
public double getGrossSales()
{
return grossSales;
} // end method getGrossSales

Fig. L 10.3 |

CommissionEmployee

class derived from Employee. (Part 1 of 2.)

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

13

14

Object-Oriented Programming: Polymorphism

Prelab Activities

Chapter 10

Name:

Programming Output

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

// calculate earnings; override abstract method earnings in Employee


public double earnings()
{
return getCommissionRate() * getGrossSales();
} // end method earnings
// return String representation of CommissionEmployee object
public String toString()
{
return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f",
"commission employee", super.toString(),
"gross sales", getGrossSales(),
"commission rate", getCommissionRate() );
} // end method toString
} // end class CommissionEmployee

Fig. L 10.3 |

CommissionEmployee

class derived from Employee. (Part 2 of 2.)

27. What is output by the following code segment? Assume that the code appears in the main method of an application.
1
2
3
4
5
6
7
8

SalariedEmployee employee1 =
new SalariedEmployee( "June", "Bug", "123-45-6789", 1000.00 );
CommissionEmployee employee2 =
new CommissionEmployee( "Archie", "Tic", "987-65-4321", 15000.00, 0.10 );
System.out.printf( "Employee 1:\n%s\n\n", employee1 );
System.out.printf( "Employee 2:\n%s\n\n", employee2 );

Your answer:

28. What is output by the following code segment? Assume that the code appears in the main method of an application.
1
2
3
4
5
6
7
8

Employee firstEmployee =
new SalariedEmployee( "June", "Bug", "123-45-6789", 1000.00 );
Employee secondEmployee =
new CommissionEmployee( "Archie", "Tic", "987-65-4321", 15000.00, 0.10 );
System.out.printf( "Employee 1:\n%s\n\n", firstEmployee );
System.out.printf( "Employee 2:\n%s\n\n", secondEmployee );

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Prelab Activities

15

Name:

Programming Output
Your answer:

29. What is output by the following code segment? Assume that the code follows the statements in Programming
Output Exercise 28.
1
2

SalariedEmployee salaried = ( SalariedEmployee ) firstEmployee;


System.out.printf( "salaried:\n%s\n", salaried );

Your answer:

30. What is output by the following code segment? Assume that the code follows the statements in Programming
Output Exercise 29.
1
2

CommissionEmployee commission = ( CommissionEmployee ) firstEmployee;


System.out.println( "commission:\n%s\n", commission );

Your answer:

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Prelab Activities

17

Name:

Correct the Code


Correct the Code

Name:

Date:

Section:
Determine if there is an error in each of the following program segments. If there is an error, specify whether it
is a logic error or a syntax error, circle the error in the program and write the corrected code in the space provided
after each problem. If the code does not contain an error, write no error. [Note: There may be more than one
error in a program segment.]
For questions 3133 assume the following denition of abstract class Employee.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

// Employee abstract superclass.


public abstract class Employee
{
private String firstName;
private String lastName;
// three-argument constructor
public Employee( String first, String last )
{
firstName = first;
lastName = last;
} // end three-argument Employee constructor
// return first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// return last name
public String getLastName()
{
return lastName;
} // end method getLastName
// return String representation of Employee object
public String toString()
{
return String.format( "%s %s", getFirstName(), getLastName() );
} // end method toString
// abstract method overridden by subclasses
public abstract double earnings(); // no implementation here
} // end abstract class Employee

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

18

Object-Oriented Programming: Polymorphism

Prelab Activities

Chapter 10

Name:

Correct the Code


31. The following concrete class should inherit from abstract class Employee. A TipWorker is paid by the hour
plus their tips for the week.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

// TipWorker.java
public final class TipWorker extends Employee
{
private double wage; // wage per hour
private double hours; // hours worked for week
private double tips; // tips for the week
public TipWorker( String first, String last,
double wagePerHour, double hoursWorked, double tipsEarned )
{
super( first, last );
// call superclass constructor
setWage ( wagePerHour );
setHours( hoursWorked );
setTips( tipsEarned );
}
// set the wage
public void setWage( double wagePerHour )
{
wage = ( wagePerHour < 0 ? 0 : wagePerHour );
}
// set the hours worked
public void setHours( double hoursWorked )
{
hours = ( hoursWorked >= 0 && hoursWorked < 168 ? hoursWorked : 0 );
}
// set the tips
public void setTips( double tipsEarned )
{
tips = ( tipsEarned < 0 ? 0 : tipsEarned );
}
} // end class TipWorker

Your answer:

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Prelab Activities

19

Name:

Correct the Code


32. The following code should define method toString of class TipWorker in Correct the Code Exercise 31.
1
2
3
4
5
6
7

// return a string representation of a TipWorker


public String toString()
{
return String.format(
"Tip worker: %s\n%s: $%,.2f; %s: %.2f; %s: $%,.2f\n", toString(),
"hourly wage", wage, "hours worked", hours, "tips earned", tips );
}

Your answer:

33. The following code should input information about five TipWorkers from the user and then print that information and all the TipWorkers calculated earnings.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

// Test2.java
import java.util.Scanner;
public class Test2
{
public static void main( String args[] )
{
Employee employee[];
Scanner input = new Scanner( System.in );
for ( int i = 0; i < employee.length; i++ )
{
System.out.print( "Input first name: " );
String firstName = input.nextLine();
System.out.print( "Input last name: " );
String lastName = input.nextLine();
System.out.print( "Input hours worked: " );
double hours = input.nextDouble();
System.out.print( "Input tips earned: " );
double tips = input.nextDouble();
employee[ i ] = new Employee( firstName, lastName, 2.63, hours, tips );
System.out.printf( "%s %s earned $%.2f\n", employee[ i ].getFirstName(),
employee[ i ].getLastName(), employee[ i ].earnings() );
input.nextLine(); // clear any remaining characters in the input stream
} // end for
} // end main
} // end class Test2

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

20

Object-Oriented Programming: Polymorphism

Prelab Activities

Chapter 10

Name:

Correct the Code


Your answer:

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

21

Lab Exercises
Lab Exercise 1 Payroll System Modification
Name:

Date:

Section:
This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The
problem is divided into six parts:
1. Lab Objectives
2. Description of the Problem
3. Sample Output
4. Program Template (Fig. L 10.4Fig. L 10.5)
5. Problem-Solving Tips
6. Follow-Up Question and Activity
The program template represents a complete working Java program, with one or more key lines of code replaced
with comments. Read the problem description and examine the sample output; then study the template code.
Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the
program. Compare your output with the sample output provided. Then answer the follow-up questions. The
source code for the template is available at www.deitel.com and www.prenhall.com/deitel.

Lab Objectives

This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Sixth Edition. In this lab, you will practice:

Creating a new class and adding it to an existing class hierarchy.

Using the updated class hierarchy in a polymorphic application.

The follow-up question and activity also will give you practice:

Understanding polymorphism.

Description of the Problem

(Payroll System Modication) Modify the payroll system of Figs. 10.410.9 to include an additional Employee
subclass PieceWorker that represents an employee whose pay is based on the number of pieces of merchandise
produced. Class PieceWorker should contain private instance variables wage (to store the employees wage per
piece) and pieces (to store the number of pieces produced). Provide a concrete implementation of method earnings in class PieceWorker that calculates the employees earnings by multiplying the number of pieces produced
by the wage per piece. Create an array of Employee variables to store references to objects of each concrete class
in the new Employee hierarchy. For each Employee, display its string representation and earnings.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

22

Object-Oriented Programming: Polymorphism

Lab Exercises

Chapter 10

Name:

Lab Exercise 1 Payroll System Modification


Sample Output
Employees processed polymorphically:
salaried employee: John Smith
social security number: 111-11-1111
weekly salary: $800.00
earned $800.00
hourly
social
hourly
earned

employee: Karen Price


security number: 222-22-2222
wage: $16.75; hours worked: 40.00
$670.00

commission employee: Sue Jones


social security number: 333-33-3333
gross sales: $10,000.00; commission rate: 0.06
earned $600.00
base-salaried commission employee: Bob Lewis
social security number: 444-44-4444
gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00
earned $500.00
piece worker: Rick Bridges
social security number: 555-55-5555
wage per piece: $2.25; pieces produced: 400
earned $900.00

Program Template
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

// Lab Exercise 1: PieceWorker.java


// PieceWorker class extends Employee.
public class PieceWorker extends Employee
{
/* declare instance variable wage */
/* declare instance variable pieces */
// five-argument constructor
public PieceWorker( String first, String last, String ssn,
double wagePerPiece, int piecesProduced )
{
/* write code to initialize a PieceWorker */
} // end five-argument PieceWorker constructor
// set wage
/* write a set method that validates and sets the PieceWorker's wage */
// return wage
/* write a get method that returns the PieceWorker's wage */
// set pieces produced
/* write a set method that validates and sets the number of pieces produced */

Fig. L 10.4 |

PieceWorker.java.

(Part 1 of 2.)

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Lab Exercises

23

Name:

Lab Exercise 1 Payroll System Modification

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

// return pieces produced


/* write a get method that returns the number of pieces produced */
// calculate earnings; override abstract method earnings in Employee
public double earnings()
{
/* write code to return the earnings for a PieceWorker */
} // end method earnings
// return String representation of PieceWorker object
public String toString()
{
/* write code to return a string representation of a PieceWorker */
} // end method toString
} // end class PieceWorker

Fig. L 10.4 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

PieceWorker.java.

(Part 2 of 2.)

// Lab Exercise 1: PayrollSystemTest.java


// Employee hierarchy test program.
public class PayrollSystemTest
{
public static void main( String args[] )
{
// create five-element Employee array
Employee employees[] = new Employee[ 5 ];
// initialize array with Employees
employees[ 0 ] = new SalariedEmployee(
"John", "Smith", "111-11-1111", 800.00 );
employees[ 1 ] = new HourlyEmployee(
"Karen", "Price", "222-22-2222", 16.75, 40 );
employees[ 2 ] = new CommissionEmployee(
"Sue", "Jones", "333-33-3333", 10000, .06 );
employees[ 3 ] = new BasePlusCommissionEmployee(
"Bob", "Lewis", "444-44-4444", 5000, .04, 300 );
/* create a PieceWoker object and assign it to employees[ 4 ] */
System.out.println( "Employees processed polymorphically:\n" );
// generically process each element in array employees
for ( Employee currentEmployee : employees )
{
System.out.println( currentEmployee ); // invokes toString
System.out.printf(
"earned $%,.2f\n\n", currentEmployee.earnings() );
} // end for
} // end main
} // end class PayrollSystemTest

Fig. L 10.5 |

PayrollSystemTest.java

Problem-Solving Tips
1. The PieceWorker constructor should call the superclass Employee constructor to initialize the employees name.
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

24

Object-Oriented Programming: Polymorphism

Lab Exercises

Chapter 10

Name:

Lab Exercise 1 Payroll System Modification


2. The number of pieces produced should be greater than or equal to 0. Place this logic in the set method
for the pieces variable.
3. The wage should be greater than or equal to 0. Place this logic in the set method for the wage variable.
4. The main method must explicitly create a new PieceWorker object and assign it to an element of the
employees array.
5. If you have any questions as you proceed, ask your lab instructor for assistance.

Follow-Up Question and Activity


1. Explain the line of code in your PayrollSystemTests main method that calls method earnings. Why can
that line invoke method earnings on every element of the employees array?

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Lab Exercises

25

Name:

Lab Exercise 2 Accounts Payable System Modification


Lab Exercise 2 Accounts Payable System Modification

Name:

Date:

Section:
This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The
problem is divided into six parts:
1. Lab Objectives
2. Description of the Problem
3. Sample Output
4. Program Template (Fig. L 10.6Fig. L 10.9)
5. Problem-Solving Tips
6. Follow-Up Question and Activity
The program template represents a complete working Java program, with one or more key lines of code replaced
with comments. Read the problem description and examine the sample output; then study the template code.
Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the
program. Compare your output with the sample output provided. Then answer the follow-up question. The
source code for the template is available at www.deitel.com and www.prenhall.com/deitel.

Lab Objectives

This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Sixth Edition. In this lab you will practice:

Provide additional polymorphic processing capabilities to an inheritance hierarchy by implementing an


interface.

Using the instanceof operator to determine whether a variable refers to an object that has an is-a relationship with a particular class.

The follow-up question and activity will also give you practice:

Comparing interfaces and abstract classes.

Description of the Problem

(Accounts Payable System Modication) In this exercise, we modify the accounts payable application of
Figs. 10.1110.15 to include the complete functionality of the payroll application. The application should still
process two Invoice objects, but now should process one object of each of the four Employee subclasses
(Figs. 10.510.8). If the object currently being processed is a BasePlusCommissionEmployee, the application
should increase the BasePlusCommissionEmployees base salary by 10%. Finally, the application should output
the payment amount for each object. Complete the following steps to create the new application:
a) Modify classes HourlyEmployee and CommissionEmployee to place them in the Payable hierarchy as subclasses of the version of Employee that implements Payable (Fig. 10.13). [Hint: Change the name of method
earnings to getPaymentAmount in each subclass so that the class satisfies its inherited contract with interface
Payable.]
b) Modify class BasePlusCommissionEmployee such that it extends the version of class CommissionEmployee
created in Part a.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

26

Object-Oriented Programming: Polymorphism

Lab Exercises

Chapter 10

Name:

Lab Exercise 2 Accounts Payable System Modification


c) Modify

PayableInterfaceTest to polymorphically process two Invoices, one SalariedEmployee, one


HourlyEmployee, one CommissionEmployee and one BasePlusCommissionEmployee. First output a string
representation of each Payable object. Next, if an object is a BasePlusCommissionEmployee, increase its base
salary by 10%. Finally, output the payment amount for each Payable object.

Sample Output
Invoices and Employees processed polymorphically:
invoice:
part number: 01234 (seat)
quantity: 2
price per item: $375.00
payment due: $750.00
invoice:
part number: 56789 (tire)
quantity: 4
price per item: $79.95
payment due: $319.80
salaried employee: John Smith
social security number: 111-11-1111
weekly salary: $800.00
payment due: $800.00
hourly employee: Karen Price
social security number: 222-22-2222
hourly wage: $16.75; hours worked: 40.00
payment due: $670.00
commission employee: Sue Jones
social security number: 333-33-3333
gross sales: $10,000.00; commission rate: 0.06
payment due: $600.00
base-salaried commission employee: Bob Lewis
social security number: 444-44-4444
gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00
new base salary with 10% increase is: $330.00
payment due: $530.00

Program Template
1
2
3
4
5
6
7
8

// Lab Exercise 2: HourlyEmployee.java


// HourlyEmployee class extends Employee, which implements Payable.
public class HourlyEmployee extends Employee
{
private double wage; // wage per hour
private double hours; // hours worked for week

Fig. L 10.6 |

HourlyEmployee.java.

(Part 1 of 2.)

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Lab Exercises

Name:

Lab Exercise 2 Accounts Payable System Modification

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

// five-argument constructor
public HourlyEmployee( String first, String last, String ssn,
double hourlyWage, double hoursWorked )
{
super( first, last, ssn );
setWage( hourlyWage ); // validate and store hourly wage
setHours( hoursWorked ); // validate and store hours worked
} // end five-argument HourlyEmployee constructor
// set wage
public void setWage( double hourlyWage )
{
wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage;
} // end method setWage
// return wage
public double getWage()
{
return wage;
} // end method getWage
// set hours worked
public void setHours( double hoursWorked )
{
hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ?
hoursWorked : 0.0;
} // end method setHours
// return hours worked
public double getHours()
{
return hours;
} // end method getHours
// calculate earnings; implement interface Payable method not
// implemented by superclass Employee
/* write a method header to satisfy the Payable interface */
{
if ( getHours() <= 40 ) // no overtime
return getWage() * getHours();
else
return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5;
} // end method getPaymentAmount
// return String representation of HourlyEmployee object
public String toString()
{
return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f",
super.toString(), "hourly wage", getWage(),
"hours worked", getHours() );
} // end method toString
} // end class HourlyEmployee

Fig. L 10.6 |

HourlyEmployee.java.

(Part 2 of 2.)

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

27

28

Object-Oriented Programming: Polymorphism

Lab Exercises

Chapter 10

Name:

Lab Exercise 2 Accounts Payable System Modification


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

// Lab Exercise 2: CommissionEmployee.java


// CommissionEmployee class extends Employee, which implements Payable.
public class CommissionEmployee extends Employee
{
private double grossSales; // gross weekly sales
private double commissionRate; // commission percentage
// five-argument constructor
public CommissionEmployee( String first, String last, String ssn,
double sales, double rate )
{
super( first, last, ssn );
setGrossSales( sales );
setCommissionRate( rate );
} // end five-argument CommissionEmployee constructor
// set commission rate
public void setCommissionRate( double rate )
{
commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
} // end method setCommissionRate
// return commission rate
public double getCommissionRate()
{
return commissionRate;
} // end method getCommissionRate
// set gross sales amount
public void setGrossSales( double sales )
{
grossSales = ( sales < 0.0 ) ? 0.0 : sales;
} // end method setGrossSales
// return gross sales amount
public double getGrossSales()
{
return grossSales;
} // end method getGrossSales
// calculate earnings; implement interface Payable method not
// implemented by superclass Employee
/* write a method header to satisfy the Payable interface */
{
return getCommissionRate() * getGrossSales();
} // end method getPaymentAmount
// return String representation of CommissionEmployee object
public String toString()
{
return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f",
"commission employee", super.toString(),
"gross sales", getGrossSales(),
"commission rate", getCommissionRate() );
} // end method toString
} // end class CommissionEmployee

Fig. L 10.7 |

CommissionEmployee.java.
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Lab Exercises

Name:

Lab Exercise 2 Accounts Payable System Modification

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

// Lab Exercise 2: BasePlusCommissionEmployee.java


// BasePlusCommissionEmployee class extends CommissionEmployee.
public class BasePlusCommissionEmployee extends CommissionEmployee
{
private double baseSalary; // base salary per week
// six-argument constructor
public BasePlusCommissionEmployee( String first, String last,
String ssn, double sales, double rate, double salary )
{
super( first, last, ssn, sales, rate );
setBaseSalary( salary ); // validate and store base salary
} // end six-argument BasePlusCommissionEmployee constructor
// set base salary
public void setBaseSalary( double salary )
{
baseSalary = ( salary < 0.0 ) ? 0.0 : salary; // non-negative
} // end method setBaseSalary
// return base salary
public double getBaseSalary()
{
return baseSalary;
} // end method getBaseSalary
// calculate earnings; override CommissionEmployee implementation of
// interface Payable method
/* write a method header to satisfy the Payable interface */
{
/* calculate and return the BasePlusCommissionEmployee's earnings */
} // end method getPaymentAmount
// return String representation of BasePlusCommissionEmployee object
public String toString()
{
return String.format( "%s %s; %s: $%,.2f",
"base-salaried", super.toString(),
"base salary", getBaseSalary() );
} // end method toString
} // end class BasePlusCommissionEmployee

Fig. L 10.8 |
1
2
3
4
5
6
7
8
9
10

BasePlusCommissionEmployee.java.

// Lab Exercise 2: PayableInterfaceTest.java


// Tests interface Payable.
public class PayableInterfaceTest
{
public static void main( String args[] )
{
// create six-element Payable array
Payable payableObjects[] = new Payable[ 6 ];

Fig. L 10.9 |

PayableInterfaceTest.java.

(Part 1 of 2.)

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

29

30

Object-Oriented Programming: Polymorphism

Lab Exercises

Chapter 10

Name:

Lab Exercise 2 Accounts Payable System Modification

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

// populate array with objects that implement Payable


payableObjects[ 0 ] = new Invoice( "01234", "seat", 2, 375.00 );
payableObjects[ 1 ] = new Invoice( "56789", "tire", 4, 79.95 );
payableObjects[ 2 ] =
new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );
payableObjects[ 3 ] =
/* create an HourlyEmployee object */
payableObjects[ 4 ] =
/* create a CommissionEmployee object */
payableObjects[ 5 ] =
/* create a BasePlusCommissionEmployee object */
System.out.println(
"Invoices and Employees processed polymorphically:\n" );
// generically process each element in array payableObjects
for ( Payable currentPayable : payableObjects )
{
// output currentPayable and its appropriate payment amount
System.out.printf( "%s \n", currentPayable.toString() );
/* write code to determine whether currentPayable is a
BasePlusCommissionEmployee object */
{
/* write code to give a raise */
/* write code to ouput results of the raise */
} // end if
System.out.printf( "%s: $%,.2f\n\n",
"payment due", currentPayable.getPaymentAmount() );
} // end for
} // end main
} // end class PayableInterfaceTest

Fig. L 10.9 |

PayableInterfaceTest.java.

(Part 2 of 2.)

Problem-Solving Tips
1. Every class that implements interface Payable must declare a method called getPaymentAmount.
2. Class BasePlusCommissionEmployee must use its superclasss getPaymentAmount method along with its
own base salary to calculate its total earnings.
3. Use the instanceof operator in PayableInterfaceTest to determine whether each object is a BasePlusCommissionEmployee object.
4. If you have any questions as you proceed, ask your lab instructor for assistance.

Follow-Up Question and Activity


1. Discuss the benefits and disadvantages of extending an abstract class vs. implementing an interface.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Lab Exercises

31

Name:

Debugging
Debugging

Name:

Date:

Section:
The program in this section does not compile. Fix all the syntax errors so that the program will compile successfully. Once the program compiles, execute the program, and compare the output with the sample output; then
eliminate any logic errors that may exist. The sample output demonstrates what the programs output should be
once the programs code is corrected. The source code is available at www.deitel.com and at www.prenhall.com/
deitel.

Sample Output
Point: [7, 11]
Circle: Center = [22, 8]; Radius = 3.500000
Cylinder: Center = [10, 10]; Radius = 3.300000; Height = 10.000000
Point: [7, 11]
Area = 0.00
Volume = 0.00
Circle: Center = [22, 8]; Radius = 3.500000
Area = 38.48
Volume = 0.00
Cylinder: Center = [10, 10]; Radius = 3.300000; Height = 10.000000
Area = 275.77
Volume = 342.12

Broken Code
1
2
3
4
5
6
7
1
2
3
4
5
6
7
8
9
10
11
12

// Shape.java
// Definition of interface Shape
public interface Shape
{
public abstract String getName(); // return shape name
} // end interface Shape

// Point.java
// Definition of class Point
public class Point implements Shape
{
protected int x, y; // coordinates of the Point
// no-argument constructor
public Point()
{
setPoint( 0, 0 );
}
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

32

Object-Oriented Programming: Polymorphism

Lab Exercises

Chapter 10

Name:

Debugging

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
1
2
3
4
5
6

// constructor
public Point( int xCoordinate, int yCoordinate )
{
setPoint( xCoordinate, yCoordinate );
}
// Set
public
{
x =
y =
}

x and y coordinates of Point


void setPoint( int xCoordinate, int yCoordinate )
xCoordinate;
yCoordinate;

// get x coordinate
public int getX()
{
return x;
}
// get y coordinate
public int getY()
{
return y;
}
// convert point into String representation
public String toString()
{
return String.format( "[%d, %d]", x, y );
}
// calculate area
public double area()
{
return 0.0;
}
// calculate volume
public double volume()
{
return 0.0;
}
// return shape name
public String getName()
{
return "Point";
}
} // end class Point

// Circle.java
// Definition of class Circle
public class Circle extends Point
{
protected double radius;

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Lab Exercises

Name:

Debugging

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
1
2
3
4
5
6
7

// no-argument constructor
public Circle()
{
// implicit call to superclass constructor here
setRadius( 0 );
}
// constructor
public Circle( double circleRadius, int xCoordinate, int yCoordinate )
{
super( xCoordinate, yCoordinate ); // call superclass constructor
}

setRadius( circleRadius );

// set radius of Circle


public void setRadius( double circleRadius )
{
radius = ( circleRadius >= 0 ? circleRadius : 0 );
}
// get radius of Circle
public double getRadius()
{
return radius;
}
// calculate area of Circle
public double area()
{
return Math.PI * radius * radius;
}
// convert Circle to a String represention
public String toString()
{
return String.format( "Center = %s; Radius = %f",
super.toString(), radius );
}
// return shape name
public String getName()
{
return "Circle";
}
} // end class Circle

// Cylinder.java
// Definition of class Cylinder.
public class Cylinder extends Circle
{
protected double height; // height of Cylinder

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

33

34

Object-Oriented Programming: Polymorphism

Lab Exercises

Chapter 10

Name:

Debugging

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

// no-argument constructor
public Cylinder()
{
// implicit call to superclass constructor here
setHeight( 0 );
}
// constructor
public Cylinder( double cylinderHeight, double cylinderRadius,
int xCoordinate, int yCoordinate )
{
// call superclass constructor
super( cylinderRadius, xCoordinate, yCoordinate );
}

setHeight( cylinderHeight );

// set height of Cylinder


public void setHeight( double cylinderHeight )
{
height = ( cylinderHeight >= 0 ? cylinderHeight : 0 );
}
// get height of Cylinder
public double getHeight()
{
return height;
}
// calculate area of Cylinder (i.e., surface area)
public double area()
{
return 2 * super.area() + 2 * Math.PI * radius * height;
}
// calculate volume of Cylinder
public double volume()
{
return super.area() * height;
}
// convert Cylinder to a String representation
public String toString()
{
return String.format( "%s; Height = %f",
super.toString(), height );
}
// return shape name
public String getName()
{
return "Cylinder";
}
} // end class Cylinder

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Lab Exercises

Name:

Debugging

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

// Test.java
// Test Point, Circle, Cylinder hierarchy with interface Shape.
public class Test
{
// test Shape hierarchy
public static void main( String args[] )
{
// create shapes
Point point = new Point( 7, 11 );
Circle circle = new Circle( 3.5, 22, 8 );
Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );
Cylinder arrayOfShapes[] = new Cylinder[ 3 ]; // create Shape array
// aim arrayOfShapes[ 0 ] at subclass Point object
arrayOfShapes[ 0 ] = ( Cylinder ) point;
// aim arrayOfShapes[ 1 ] at subclass Circle object
arrayOfShapes[ 1 ] = ( Cylinder ) circle;
// aim arrayOfShapes[ 2 ] at subclass Cylinder object
arrayOfShapes[ 2 ] = ( Cylinder ) cylinder;
// get name and String representation of each shape
System.out.printf( "%s: %s\n%s: %s\n%s: %s\n", point.getName(),
point, circle.getName(), circle, cylinder.getName(), cylinder );
// get name, area and volume of each shape in arrayOfShapes
for ( Shape shape : arrayOfShapes )
{
System.out.printf( "\n\n%s: %s\nArea = %.2f\nVolume = %.2f\n",
shape.getName(), shape, shape.area(), shape.volume() );
} // end for
} // end main
} // end class Test

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

35

Chapter 10

Object-Oriented Programming: Polymorphism

37

Postlab Activities
Coding Exercises
Name:

Date:

Section:
These coding exercises reinforce the lessons learned in the lab and provide additional programming experience
outside the classroom and laboratory environment. They serve as a review after you have successfully completed
the Prelab Activities and Lab Exercises.
For each of the following problems, write a program or a program segment that performs the specied action.
1. Write an empty class declaration for an abstract class called Shape.

2. In the class from Coding Exercise 1, create a protected instance variable shapeName of type String, and write
an accessor method getName for obtaining its value.

3. In the class of Coding Exercise 2, define an abstract method getArea that returns a double representation
of a specific shapes area. Subclasses of this class must implement getArea to calculate a specific shapes area.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

38

Object-Oriented Programming: Polymorphism

Postlab Activities

Chapter 10

Name:

Coding Exercises
4. Define a class Square that inherits from class Shape from Coding Exercise 3; it should contain an instance
variable side, which represents the length of a side of the square. Provide a constructor that takes one argument representing the side of the square and sets the side variable. Ensure that the side is greater than or
equal to 0. The constructor should set the inherited shapeName variable to the string "Square".

5. The Square class from Coding Exercise 4 should implement the getArea method of its abstract superclass;
this implementation should compute the area of the square and return the result.

6. Define a class Rectangle that inherits from class Shape of Coding Exercise 3. The new class should contain
instance variables length and width. Provide a constructor that takes two arguments representing the length
and width of the rectangle, sets the two variables and sets the inherited shapeName variable to the string
"Rectangle". Ensure that the length and width are both greater than or equal to 0.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Postlab Activities

39

Name:

Coding Exercises
7. The Rectangle class from Coding Exercise 6 should also implement the getArea method of its abstract superclass; this implementation should compute the area of the rectangle and return the result.

8. Write an application that tests the Square and Rectangle classes from Coding Exercises 5 and 7, respectively.
Create an array of type Shape that holds an instance of Square and an instance of Rectangle. The program
should polymorphically compute and display the areas of both objects. Allow a user to enter the values for
the side of the square and the length and width of the rectangle.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

Postlab Activities

41

Name:

Programming Challenges
Programming Challenges

Name:

Date:

Section:
The Programming Challenges are more involved than the Coding Exercises and may require a significant amount
of time to complete. Write a Java program for each of the problems in this section. The answers to these problems
are available at www.deitel.com and www.prenhall.com/deitel. Pseudocode, hints or sample outputs are provided for each problem to aid you in your programming.
1. (Payroll System Modication) Modify the payroll system of Figs. 10.410.9 to include private instance variable birthDate in class Employee. Use class Date of Fig. 8.7 to represent an employees birthday. Add get
methods to class Date and replace method toDateString with method toString. Assume that payroll is
processed once per month. Create an array of Employee variables to store references to the various employee
objects. In a loop, calculate the payroll for each Employee (polymorphically), and add a $100.00 bonus to
the persons payroll amount if the current month is the month in which the Employees birthday occurs.
Hint:

Your output should appear as follows:

Date object constructor for date 6/15/1944


Date object constructor for date 12/29/1960
Date object constructor for date 9/8/1954
Date object constructor for date 3/2/1965
Employees processed individually:
salaried employee: John Smith
social security number: 111-11-1111
birth date: 6/15/1944
weekly salary: $800.00
earned: $800.00
hourly employee: Karen Price
social security number: 222-22-2222
birth date: 12/29/1960
hourly wage: $16.75; hours worked: 40.00
earned: $670.00
commission employee: Sue Jones
social security number: 333-33-3333
birth date: 9/8/1954
gross sales: $10,000.00; commission rate: 0.06
earned: $600.00
base-salaried commission employee: Bob Lewis
social security number: 444-44-4444
birth date: 3/2/1965
gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00
earned: $500.00
Enter the current month (1 - 12): 3

(continued next page...)

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

42

Object-Oriented Programming: Polymorphism

Postlab Activities

Chapter 10

Name:

Programming Challenges

Employees processed polymorphically:


salaried employee: John Smith
social security number: 111-11-1111
birth date: 6/15/1944
weekly salary: $800.00
earned $800.00
hourly employee: Karen Price
social security number: 222-22-2222
birth date: 12/29/1960
hourly wage: $16.75; hours worked: 40.00
earned $670.00
commission employee: Sue Jones
social security number: 333-33-3333
birth date: 9/8/1954
gross sales: $10,000.00; commission rate: 0.06
earned $600.00
base-salaried commission employee: Bob Lewis
social security number: 444-44-4444
birth date: 3/2/1965
gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00
new base salary with 10% increase is: $330.00
earned $530.00 plus $100.00 birthday bonus
Employee
Employee
Employee
Employee

0
1
2
3

is
is
is
is

a
a
a
a

SalariedEmployee
HourlyEmployee
CommissionEmployee
BasePlusCommissionEmployee

2. (Shape Hierarchy) Implement the Shape hierarchy shown in Fig. 9.3. Each TwoDimensionalShape should
contain method getArea to calculate the area of the two-dimensional shape. Each ThreeDimensionalShape
should have methods getArea and getVolume to calculate the surface area and volume, respectively, of the
three-dimensional shape. Create a program that uses an array of Shape references to objects of each concrete
class in the hierarchy. The program should print a text description of the object to which each array element
refers. Also, in the loop that processes all the shapes in the array, determine whether each shape is a TwoDimensionalShape or a ThreeDimensionalShape. If a shape is a TwoDimensionalShape, display its area. If
a shape is a ThreeDimensionalShape, display its area and volume.
Hint:

Your output should appear as follows:

Circle: [22, 88] radius: 4


Circle's area is 50
Square: [71, 96] side: 10
Square's area is 100
Sphere: [8, 89] radius: 2
Sphere's area is 50
Sphere's volume is 33
Cube: [79, 61] side: 8
Cube's area is 384
Cube's volume is 512

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.