jhtp8lm_im_10[1]

70
10 Object-Oriented Programming: Polymorphism 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 object’s type at execution time. To declare and implement interfaces.

Upload: sana-khan

Post on 24-Oct-2015

465 views

Category:

Documents


0 download

DESCRIPTION

jhtp8LM_IM_10

TRANSCRIPT

10Object-Oriented Programming: Polymorphism

O B J E C T I V E SIn 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 object’s type at execution time.

■ To declare and implement interfaces.

Chapter 10 Object-Oriented Programming: Polymorphism 3

Name: Date:

Section:

Assignment Checklist

Exercises Assigned: Circle assignments Date Due

Prelab Activities

Matching YES NO

Fill in the Blank YES NO

Short Answer YES NO

Programming Output YES NO

Correct the Code YES NO

Lab Exercises

Exercise 1 — Payroll System Modification YES NO

Follow-Up Question and Activity 1

Exercise 2 — Accounts Payable System Modification YES NO

Follow-Up Question and Activity 1

Debugging YES NO

Postlab Activities

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

Programming Challenges 1, 2

Chapter 10 Object-Oriented Programming: Polymorphism 5

Prelab Activities

Name: Date:

Section:

Matching

After reading Chapter 10 of Java How to Program: 8/e, answer the given questions. The questions are intendedto 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 theterm.

Term Description

I

J

H

L

F

K

E

D

B

C

G

A

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 method

11. abstract class

12. interface

a) Can be used in place of an abstract class when there is no defaultimplementation to inherit.

b) Indicates that a method cannot be overridden or that a class can-not be a superclass.

c) Class method which returns the name of the class associated withthe Class object.

d) An operator that returns true if its left operand (a variable of a ref-erence type) has the is-a relationship with its right operand (a classor interface name).

e) Uses superclass references to manipulate sets of subclass objects ina 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 withthe signature specified in the interface declaration.

i) Must be overridden in a subclass; otherwise, the subclass must bedeclared abstract.

j) Returns an object that can be used to determine informationabout the object’s class.

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

l) Classes in the java.lang package that are used to create objectscontaining values of primitive types.

Prelab Activities Name:

Fill in the Blank

Chapter 10 Object-Oriented Programming: Polymorphism 7

Name: Date:

Section:

Fill in the Blank

Fill in the blanks for each of the following statements:

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

14. Although we cannot instantiate objects of abstract superclasses, we can declare references of abstract su-perclass types.

15. It is a syntax error if a class with one or more abstract methods is not explicitly declared abstract .

16. It is possible to assign a superclass reference to a subclass variable by downcasting the reference to the sub-class type.

17. A(n) interface 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 ofthe method found in the subclass .

19. The instanceof operator determines whether the type of the object to which its left operand refers hasan is-a relationship with the type specified as its right operand.

20. To use an interface, a class must specify that it implements the interface and must declare every methodin the interface with the signatures specified in the interface declaration.

21. When a class implements an interface, it establishes an is-a relationship with the interface type.

Prelab Activities Name:

Short Answer

Chapter 10 Object-Oriented Programming: Polymorphism 9

Name: Date:

Section:

Short Answer

In the space provided, answer each of the given questions. Your answers should be concise; aim for two or threesentences.

22. Describe the concept of polymorphism.

Polymorphism makes it possible to design and implement systems that are more easily extensible. Programs canbe written to process objects generically as one type, and new classes can be added with little or no modificationsto the generic part of the program. For example, a program can be designed to draw shapes rather than to drawrectangles, ovals and lines. Each shape object would know how to draw itself.

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

Declaring a method final means that the method cannot be overridden in a subclass. Declaring a class finalmeans that it cannot be a superclass (i.e., a class cannot inherit from a final class). Methods in a final class areimplicitly final.

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

A compilation error occurs in this case. Every method in the interface must be implemented, or the class mustbe declared abstract to prevent this compilation error.

25. Describe how to determine the class name of an object’s class.

Call method getClass on an object to obtain an object of type Class that represents the object’s type. Then callthe Class object’s getName method to get a String containing the class’s name.

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

An abstract class can be used as a superclass and to declare variables that can store references to objects of theabstract class’s subclass. An abstract class cannot be used to create objects. A concrete class can be used to createobjects and declare variables. In addition, a concrete class can also be used as a superclass as long as it is not de-clared final.

Prelab Activities Name:

Programming Output

Chapter 10 Object-Oriented Programming: Polymorphism 11

Name: Date:

Section:

Programming Output

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

Use the class definitions in Fig. L 10.1–Fig. L 10.3 when answering Programming Output Exercises 27–30.

1 // Employee.java2 // Employee abstract superclass.34 public abstract class Employee 5 {6 private String firstName;7 private String lastName;8 private String socialSecurityNumber;9

10 // three-argument constructor11 public Employee( String first, String last, String ssn )12 {13 firstName = first;14 lastName = last;15 socialSecurityNumber = ssn;16 } // end three-argument Employee constructor1718 // set first name19 public void setFirstName( String first )20 {21 firstName = first;22 } // end method setFirstName2324 // return first name25 public String getFirstName()26 {27 return firstName;28 } // end method getFirstName2930 // set last name31 public void setLastName( String last )32 {33 lastName = last;34 } // end method setLastName3536 // return last name37 public String getLastName()38 {39 return lastName;40 } // end method getLastName41

Fig. L 10.1 | Employee abstract superclass. (Part 1 of 2.)

Prelab Activities Name:

Programming Output

12 Object-Oriented Programming: Polymorphism Chapter 10

42 // set social security number43 public void setSocialSecurityNumber( String ssn )44 {45 socialSecurityNumber = ssn; // should validate46 } // end method setSocialSecurityNumber4748 // return social security number49 public String getSocialSecurityNumber()50 {51 return socialSecurityNumber;52 } // end method getSocialSecurityNumber5354 // return String representation of Employee object55 public String toString()56 {57 return String.format( "%s %s\nsocial security number: %s", 58 getFirstName(), getLastName(), getSocialSecurityNumber() );59 } // end method toString6061 // abstract method overridden by subclasses 62 public abstract double earnings(); // no implementation here63 } // end abstract class Employee

1 // SalariedEmployee.java2 // SalariedEmployee class extends Employee.34 public class SalariedEmployee extends Employee 5 {6 private double weeklySalary;78 // four-argument constructor9 public SalariedEmployee( String first, String last, String ssn,

10 double salary )11 {12 super( first, last, ssn ); // pass to Employee constructor13 setWeeklySalary( salary ); // validate and store salary14 } // end four-argument SalariedEmployee constructor1516 // set salary17 public void setWeeklySalary( double salary )18 {19 weeklySalary = salary < 0.0 ? 0.0 : salary;20 } // end method setWeeklySalary2122 // return salary23 public double getWeeklySalary()24 {25 return weeklySalary;26 } // end method getWeeklySalary2728 // calculate earnings; override abstract method earnings in Employee29 public double earnings() 30 {

Fig. L 10.2 | SalariedEmployee class derived from Employee. (Part 1 of 2.)

Fig. L 10.1 | Employee abstract superclass. (Part 2 of 2.)

Prelab Activities Name:

Programming Output

Chapter 10 Object-Oriented Programming: Polymorphism 13

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

1 // CommissionEmployee.java2 // CommissionEmployee class extends Employee.34 public class CommissionEmployee extends Employee 5 {6 private double grossSales; // gross weekly sales7 private double commissionRate; // commission percentage89 // 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 constructor1718 // set commission rate19 public void setCommissionRate( double rate )20 {21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;22 } // end method setCommissionRate2324 // return commission rate25 public double getCommissionRate()26 {27 return commissionRate;28 } // end method getCommissionRate2930 // set gross sales amount31 public void setGrossSales( double sales )32 {33 grossSales = ( sales < 0.0 ) ? 0.0 : sales;34 } // end method setGrossSales3536 // return gross sales amount37 public double getGrossSales()38 {39 return grossSales;40 } // end method getGrossSales41

Fig. L 10.3 | CommissionEmployee class derived from Employee. (Part 1 of 2.)

Fig. L 10.2 | SalariedEmployee class derived from Employee. (Part 2 of 2.)

Prelab Activities Name:

Programming Output

14 Object-Oriented Programming: Polymorphism Chapter 10

27. What is output by the following code segment? Assume that the code appears in the main method of an ap-plication.

Your answer:

28. What is output by the following code segment? Assume that the code appears in the main method of an ap-plication.

42 // calculate earnings; override abstract method earnings in Employee43 public double earnings() 44 { 45 return getCommissionRate() * getGrossSales(); 46 } // end method earnings 4748 // return String representation of CommissionEmployee object49 public String toString() 50 { 51 return String.format( "%s: %s\n%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

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

Employee 1:salaried employee: June Bugsocial security number: 123-45-6789weekly salary: $1,000.00

Employee 2:commission employee: Archie Ticsocial security number: 987-65-4321gross sales: $15,000.00; commission rate: 0.10

1 Employee firstEmployee =2 new SalariedEmployee( "June", "Bug", "123-45-6789", 1000.00 );34 Employee secondEmployee = 5 new CommissionEmployee( "Archie", "Tic", "987-65-4321", 15000.00, 0.10 );

Fig. L 10.3 | CommissionEmployee class derived from Employee. (Part 2 of 2.)

Prelab Activities Name:

Programming Output

Chapter 10 Object-Oriented Programming: Polymorphism 15

Your answer:

29. What is output by the following code segment? Assume that the code follows the statements in ProgrammingOutput Exercise 28.

Your answer:

30. What is output by the following code segment? Assume that the code follows the statements in ProgrammingOutput Exercise 29.

Your answer: Although the cast in line 1 is allowed at compile time, this results in a ClassCastException at run-time because a SalariedEmployee is not a CommissionEmployee.

67 System.out.printf( "Employee 1:\n%s\n\n", firstEmployee );8 System.out.printf( "Employee 2:\n%s\n\n", secondEmployee );

Employee 1:salaried employee: June Bugsocial security number: 123-45-6789weekly salary: $1,000.00

Employee 2:commission employee: Archie Ticsocial security number: 987-65-4321gross sales: $15,000.00; commission rate: 0.10

1 SalariedEmployee salaried = ( SalariedEmployee ) firstEmployee;2 System.out.printf( "salaried:\n%s\n", salaried );

salaried:salaried employee: June Bugsocial security number: 123-45-6789weekly salary: $1,000.00

1 CommissionEmployee commission = ( CommissionEmployee ) firstEmployee;2 System.out.println( "commission:\n%s\n", commission );

Exception in thread "main" java.lang.ClassCastException: SalariedEmployee at Test.main(Test.java:17)

Prelab Activities Name:

Correct the Code

Chapter 10 Object-Oriented Programming: Polymorphism 17

Name: Date:

Section:

Correct the Code

Determine if there is an error in each of the following program segments. If there is an error, specify whether itis a logic error or a syntax error, circle the error in the program and write the corrected code in the space providedafter each problem. If the code does not contain an error, write “no error.” [Note: There may be more than oneerror in a program segment.]

For questions 31–33 assume the following definition of abstract class Employee.

1 // Employee abstract superclass.23 public abstract class Employee 4 {5 private String firstName;6 private String lastName;78 // three-argument constructor9 public Employee( String first, String last )

10 {11 firstName = first;12 lastName = last;13 } // end three-argument Employee constructor1415 // return first name16 public String getFirstName()17 {18 return firstName;19 } // end method getFirstName2021 // return last name22 public String getLastName()23 {24 return lastName;25 } // end method getLastName2627 // return String representation of Employee object28 public String toString()29 {30 return String.format( "%s %s", getFirstName(), getLastName() );31 } // end method toString3233 // abstract method overridden by subclasses 34 public abstract double earnings(); // no implementation here35 } // end abstract class Employee

Prelab Activities Name:

Correct the Code

18 Object-Oriented Programming: Polymorphism Chapter 10

31. The following concrete class should inherit from abstract class Employee. A TipWorker is paid by the hourplus their tips for the week.

Your answer: Class TipWorker did not implement abstract method earnings that was inherited from classEmployee. The class must implement this method to be a concrete class.

1 // TipWorker.java2 public final class TipWorker extends Employee3 {4 private double wage; // wage per hour5 private double hours; // hours worked for week6 private double tips; // tips for the week78 public TipWorker( String first, String last, 9 double wagePerHour, double hoursWorked, double tipsEarned )

10 {11 super( first, last ); // call superclass constructor12 setWage ( wagePerHour );13 setHours( hoursWorked );14 setTips( tipsEarned );15 }16 17 // set the wage18 public void setWage( double wagePerHour )19 {20 wage = ( wagePerHour < 0 ? 0 : wagePerHour );21 }22 23 // set the hours worked24 public void setHours( double hoursWorked )25 {26 hours = ( hoursWorked >= 0 && hoursWorked < 168 ? hoursWorked : 0 ); 27 }28 29 // set the tips30 public void setTips( double tipsEarned )31 { 32 tips = ( tipsEarned < 0 ? 0 : tipsEarned );33 }34 } // end class TipWorker

1 // TipWorker.java2 public final class TipWorker extends Employee3 {4 private double wage; // wage per hour5 private double hours; // hours worked for week6 private double tips; // tips for the week78 public TipWorker( String first, String last, 9 double wagePerHour, double hoursWorked, double tipsEarned )

10 {11 super( first, last ); // call superclass constructor12 setWage ( wagePerHour );13 setHours( hoursWorked );14 setTips( tipsEarned );15 }

Prelab Activities Name:

Correct the Code

Chapter 10 Object-Oriented Programming: Polymorphism 19

32. The following code should define method toString of class TipWorker in Correct the Code Exercise 31.

Your answer: The call to toString in line 5 should call the superclass’s toString; otherwise, this causes infiniterecursion.

16 17 // set the wage18 public void setWage( double wagePerHour )19 {20 wage = ( wagePerHour < 0 ? 0 : wagePerHour );21 }22 23 // set the hours worked24 public void setHours( double hoursWorked )25 {26 hours = ( hoursWorked >= 0 && hoursWorked < 168 ? hoursWorked : 0 ); 27 }28 29 // set the tips30 public void setTips( double tipsEarned )31 { 32 tips = ( tipsEarned < 0 ? 0 : tipsEarned );33 }3435 36 37 38 39 40 } // end class TipWorker

1 // return a string representation of a TipWorker2 public String toString() 3 {4 return String.format( 5 "Tip worker: %s\n%s: $%,.2f; %s: %.2f; %s: $%,.2f\n", toString(), 6 "hourly wage", wage, "hours worked", hours, "tips earned", tips );7 }

1 // return a string representation of a TipWorker2 public String toString() 3 {4 return String.format( 5 "Tip worker: %s\n%s: $%,.2f; %s: %.2f; %s: $%,.2f\n", , 6 "hourly wage", wage, "hours worked", hours, "tips earned", tips );7 }

// get the TipWorker's pay public double earnings() { return ( wage * hours ) + tips;}

super.toString()

Prelab Activities Name:

Correct the Code

20 Object-Oriented Programming: Polymorphism Chapter 10

33. The following code should input information about five TipWorkers from the user and then print that in-formation and all the TipWorkers’ calculated earnings.

Your answer:

1 // Test2.java2 import java.util.Scanner;34 public class Test25 {6 public static void main( String args[] )7 {8 Employee employee[];9 Scanner input = new Scanner( System.in );

10 11 for ( int i = 0; i < employee.length; i++ )12 {13 System.out.print( "Input first name: " );14 String firstName = input.nextLine();1516 System.out.print( "Input last name: " );17 String lastName = input.nextLine();1819 System.out.print( "Input hours worked: " );20 double hours = input.nextDouble();2122 System.out.print( "Input tips earned: " );23 double tips = input.nextDouble();24 25 employee[ i ] = new Employee( firstName, lastName, 2.63, hours, tips );26 27 System.out.printf( "%s %s earned $%.2f\n", employee[ i ].getFirstName(), 28 employee[ i ].getLastName(), employee[ i ].earnings() );2930 input.nextLine(); // clear any remaining characters in the input stream31 } // end for32 } // end main33 } // end class Test2

1 // Test2.java2 import java.util.Scanner;34 public class Test25 {6 public static void main( String args[] )7 {8 Employee employee[] = new Employee[ 5 ];9 Scanner input = new Scanner( System.in );

10 11 for ( int i = 0; i < employee.length; i++ )12 {13 System.out.print( "\nInput first name: " );14 String firstName = input.nextLine();1516 System.out.print( "Input last name: " );17 String lastName = input.nextLine();

Prelab Activities Name:

Correct the Code

Chapter 10 Object-Oriented Programming: Polymorphism 21

1819 System.out.print( "Input hours worked: " );20 double hours = input.nextDouble();2122 System.out.print( "Input tips earned: " );23 double tips = input.nextDouble();24 25 employee[ i ] = new TipWorker( firstName, lastName, 2.63, hours, tips );26 27 System.out.printf( "%s %s earned $%.2f\n", employee[ i ].getFirstName(), 28 employee[ i ].getLastName(), employee[ i ].earnings() );2930 input.nextLine(); // clear any remaining characters in the input stream31 } // end for32 } // end main33 } // end class Test2

Chapter 10 Object-Oriented Programming: Polymorphism 23

Lab Exercises

Name: Date:

Section:

Lab Exercise 1 — Payroll System Modification

This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. Theproblem is divided into six parts:

1. Lab Objectives

2. Description of the Problem

3. Sample Output

4. Program Template (Fig. L 10.4–Fig. 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 replacedwith 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 theprogram. Compare your output with the sample output provided. Then answer the follow-up questions. Thesource code for the template is available at www.pearsonhighered.com/deitel.

Lab ObjectivesThis lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: 8/e. In thislab, 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 Modification) Modify the payroll system of Figs. 10.4–10.9 to include an additional Employeesubclass PieceWorker that represents an employee whose pay is based on the number of pieces of merchandiseproduced. Class PieceWorker should contain private instance variables wage (to store the employee’s wage perpiece) and pieces (to store the number of pieces produced). Provide a concrete implementation of method earn-ings in class PieceWorker that calculates the employee’s earnings by multiplying the number of pieces producedby the wage per piece. Create an array of Employee variables to store references to objects of each concrete classin the new Employee hierarchy. For each Employee, display its string representation and earnings.

Lab Exercises Name:

Lab Exercise 1 — Payroll System Modification

24 Object-Oriented Programming: Polymorphism Chapter 10

Sample Output

Program Template

Employees processed polymorphically:

salaried employee: John Smithsocial security number: 111-11-1111weekly salary: $800.00earned $800.00

hourly employee: Karen Pricesocial security number: 222-22-2222hourly wage: $16.75; hours worked: 40.00earned $670.00

commission employee: Sue Jonessocial security number: 333-33-3333gross sales: $10,000.00; commission rate: 0.06earned $600.00

base-salaried commission employee: Bob Lewissocial security number: 444-44-4444gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00earned $500.00

piece worker: Rick Bridgessocial security number: 555-55-5555wage per piece: $2.25; pieces produced: 400earned $900.00

1 // Lab Exercise 1: PieceWorker.java2 // PieceWorker class extends Employee.34 public class PieceWorker extends Employee 5 {6 7 89 // five-argument constructor

10 public PieceWorker( String first, String last, String ssn, 11 double wagePerPiece, int piecesProduced )12 {13 14 } // end five-argument PieceWorker constructor1516 // set wage17 1819 // return wage20 2122 // set pieces produced23 24

Fig. L 10.4 | PieceWorker.java. (Part 1 of 2.)

/* declare instance variable wage */ /* declare instance variable pieces */

/* write code to initialize a PieceWorker */

/* write a set method that validates and sets the PieceWorker's wage */

/* write a get method that returns the PieceWorker's wage */

/* write a set method that validates and sets the number of pieces produced */

Lab Exercises Name:

Lab Exercise 1 — Payroll System Modification

Chapter 10 Object-Oriented Programming: Polymorphism 25

25 // return pieces produced26 2728 // calculate earnings; override abstract method earnings in Employee29 public double earnings()30 {31 32 } // end method earnings3334 // return String representation of PieceWorker object35 public String toString()36 {37 38 } // end method toString39 } // end class PieceWorker

1 // Lab Exercise 1: PayrollSystemTest.java2 // Employee hierarchy test program.34 public class PayrollSystemTest 5 {6 public static void main( String args[] ) 7 {8 // create five-element Employee array9 Employee employees[] = new Employee[ 5 ];

1011 // initialize array with Employees12 employees[ 0 ] = new SalariedEmployee( 13 "John", "Smith", "111-11-1111", 800.00 );14 employees[ 1 ] = new HourlyEmployee( 15 "Karen", "Price", "222-22-2222", 16.75, 40 );16 employees[ 2 ] = new CommissionEmployee( 17 "Sue", "Jones", "333-33-3333", 10000, .06 ); 18 employees[ 3 ] = new BasePlusCommissionEmployee( 19 "Bob", "Lewis", "444-44-4444", 5000, .04, 300 );20 /* create a PieceWoker object and assign it to employees[ 4 ] */2122 System.out.println( "Employees processed polymorphically:\n" );23 24 // generically process each element in array employees25 for ( Employee currentEmployee : employees ) 26 {27 System.out.println( currentEmployee ); // invokes toString28 System.out.printf( 29 "earned $%,.2f\n\n", currentEmployee.earnings() );30 } // end for31 } // end main32 } // end class PayrollSystemTest

Fig. L 10.5 | PayrollSystemTest.java

Fig. L 10.4 | PieceWorker.java. (Part 2 of 2.)

/* write a get method that returns the number of pieces produced */

/* write code to return the earnings for a PieceWorker */

/* write code to return a string representation of a PieceWorker */

Lab Exercises Name:

Lab Exercise 1 — Payroll System Modification

26 Object-Oriented Programming: Polymorphism Chapter 10

Solution

1 // Lab Exercise 1: PieceWorker2 // PieceWorker class extends Employee.34 public class PieceWorker extends Employee 5 {6 private double wage; // wage per piece7 private int pieces; // pieces of merchandise produced in week89 // five-argument constructor

10 public PieceWorker( String first, String last, String ssn, 11 double wagePerPiece, int piecesProduced )12 {13 super( first, last, ssn );14 setWage( wagePerPiece ); // validate and store wage per piece15 setPieces( piecesProduced ); // validate and store pieces produced16 } // end five-argument PieceWorker constructor1718 // set wage19 public void setWage( double wagePerPiece )20 {21 wage = ( wagePerPiece < 0.0 ) ? 0.0 : wagePerPiece;22 } // end method setWage2324 // return wage25 public double getWage()26 {27 return wage;28 } // end method getWage2930 // set pieces produced31 public void setPieces( int piecesProduced )32 {33 pieces = ( piecesProduced < 0 ) ? 0 : piecesProduced;34 } // end method setPieces3536 // return pieces produced37 public int getPieces()38 {39 return pieces;40 } // end method getPieces4142 // calculate earnings; override abstract method earnings in Employee43 public double earnings()44 {45 return getPieces() * getWage();46 } // end method earnings4748 // return String representation of PieceWorker object49 public String toString()50 {51 return String.format( "%s: %s\n%s: $%,.2f; %s: %d", 52 "piece worker", super.toString(), 53 "wage per piece", getWage(), "pieces produced", getPieces() );54 } // end method toString55 } // end class PieceWorker

Lab Exercises Name:

Lab Exercise 1 — Payroll System Modification

Chapter 10 Object-Oriented Programming: Polymorphism 27

Problem-Solving Tips1. The PieceWorker constructor should call the superclass Employee constructor to initialize the employ-

ee’s name.

2. The number of pieces produced should be greater than or equal to 0. Place this logic in the set methodfor 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 theemployees array.

5. If you have any questions as you proceed, ask your lab instructor for assistance.

Follow-Up Question and Activity1. Explain the line of code in your PayrollSystemTest’s main method that calls method earnings. Why

can that line invoke method earnings on every element of the employees array?

This line of code uses polymorphism to ensure that each Employee’s earnings is calculated correctly. Everyelement of array employees refers to an object that is an Employee. Since class Employee declares an abstractearnings method, every concrete subclass of Employee must implement the earnings method. Also, sinceobjects can be created only from concrete classes, it is guaranteed that the object to which currentEmployeerefers during an iteration of the for statement will have an earnings method.

1 // Lab Exercise 1: PayrollSystemTest.java2 // Employee hierarchy test program.34 public class PayrollSystemTest 5 {6 public static void main( String args[] ) 7 {8 // create five-element Employee array9 Employee employees[] = new Employee[ 5 ];

1011 // initialize array with Employees12 employees[ 0 ] = new SalariedEmployee( 13 "John", "Smith", "111-11-1111", 800.00 );14 employees[ 1 ] = new HourlyEmployee( 15 "Karen", "Price", "222-22-2222", 16.75, 40 );16 employees[ 2 ] = new CommissionEmployee( 17 "Sue", "Jones", "333-33-3333", 10000, .06 ); 18 employees[ 3 ] = new BasePlusCommissionEmployee( 19 "Bob", "Lewis", "444-44-4444", 5000, .04, 300 );20 employees[ 4 ] = new PieceWorker(21 "Rick", "Bridges", "555-55-5555", 2.25, 400 );2223 System.out.println( "Employees processed polymorphically:\n" );24 25 // generically process each element in array employees26 for ( Employee currentEmployee : employees ) 27 {28 System.out.println( currentEmployee ); // invokes toString29 System.out.printf( 30 "earned $%,.2f\n\n", currentEmployee.earnings() );31 } // end for32 } // end main33 } // end class PayrollSystemTest

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

Chapter 10 Object-Oriented Programming: Polymorphism 29

Name: Date:

Section:

Lab Exercise 2 — Accounts Payable System Modification

This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. Theproblem is divided into six parts:

1. Lab Objectives

2. Description of the Problem

3. Sample Output

4. Program Template (Fig. L 10.6–Fig. 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 replacedwith 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 theprogram. Compare your output with the sample output provided. Then answer the follow-up question. Thesource code for the template is available at www.pearsonhighered.com/deitel.

Lab ObjectivesThis lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: 8/e. In thislab you will practice:

• Provide additional polymorphic processing capabilities to an inheritance hierarchy by implementing aninterface.

• Using the instanceof operator to determine whether a variable refers to an object that has an is-a rela-tionship 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 Modification) In this exercise, we modify the accounts payable application ofFigs. 10.11–10.15 to include the complete functionality of the payroll application. The application should stillprocess two Invoice objects, but now should process one object of each of the four Employee subclasses(Figs. 10.5–10.8). If the object currently being processed is a BasePlusCommissionEmployee, the applicationshould increase the BasePlusCommissionEmployee’s base salary by 10%. Finally, the application should outputthe 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 sub-classes of the version of Employee that implements Payable (Fig. 10.13). [Hint: Change the name of methodearnings to getPaymentAmount in each subclass so that the class satisfies its inherited contract with interfacePayable.]

b) Modify class BasePlusCommissionEmployee such that it extends the version of class CommissionEmployeecreated in Part a.

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

30 Object-Oriented Programming: Polymorphism Chapter 10

c) Modify PayableInterfaceTest to polymorphically process two Invoices, one SalariedEmployee, oneHourlyEmployee, one CommissionEmployee and one BasePlusCommissionEmployee. First output a stringrepresentation of each Payable object. Next, if an object is a BasePlusCommissionEmployee, increase its basesalary by 10%. Finally, output the payment amount for each Payable object.

Sample Output

Program Template

Invoices and Employees processed polymorphically:

invoice:part number: 01234 (seat)quantity: 2price per item: $375.00payment due: $750.00

invoice:part number: 56789 (tire)quantity: 4price per item: $79.95payment due: $319.80

salaried employee: John Smithsocial security number: 111-11-1111weekly salary: $800.00payment due: $800.00

hourly employee: Karen Pricesocial security number: 222-22-2222hourly wage: $16.75; hours worked: 40.00payment due: $670.00

commission employee: Sue Jonessocial security number: 333-33-3333gross sales: $10,000.00; commission rate: 0.06payment due: $600.00

base-salaried commission employee: Bob Lewissocial security number: 444-44-4444gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00new base salary with 10% increase is: $330.00payment due: $530.00

1 // Lab Exercise 2: HourlyEmployee.java2 // HourlyEmployee class extends Employee, which implements Payable.34 public class HourlyEmployee extends Employee 5 {6 private double wage; // wage per hour7 private double hours; // hours worked for week8

Fig. L 10.6 | HourlyEmployee.java. (Part 1 of 2.)

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

Chapter 10 Object-Oriented Programming: Polymorphism 31

9 // five-argument constructor10 public HourlyEmployee( String first, String last, String ssn, 11 double hourlyWage, double hoursWorked )12 {13 super( first, last, ssn );14 setWage( hourlyWage ); // validate and store hourly wage15 setHours( hoursWorked ); // validate and store hours worked16 } // end five-argument HourlyEmployee constructor1718 // set wage19 public void setWage( double hourlyWage )20 {21 wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage;22 } // end method setWage2324 // return wage25 public double getWage()26 {27 return wage;28 } // end method getWage2930 // set hours worked31 public void setHours( double hoursWorked )32 {33 hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ?34 hoursWorked : 0.0;35 } // end method setHours3637 // return hours worked38 public double getHours()39 {40 return hours;41 } // end method getHours4243 // calculate earnings; implement interface Payable method not44 // implemented by superclass Employee45 46 {47 if ( getHours() <= 40 ) // no overtime48 return getWage() * getHours();49 else50 return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5;51 } // end method getPaymentAmount5253 // return String representation of HourlyEmployee object54 public String toString()55 {56 return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f", 57 super.toString(), "hourly wage", getWage(), 58 "hours worked", getHours() );59 } // end method toString60 } // end class HourlyEmployee

Fig. L 10.6 | HourlyEmployee.java. (Part 2 of 2.)

/* write a method header to satisfy the Payable interface */

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

32 Object-Oriented Programming: Polymorphism Chapter 10

1 // Lab Exercise 2: CommissionEmployee.java2 // CommissionEmployee class extends Employee, which implements Payable.34 public class CommissionEmployee extends Employee 5 {6 private double grossSales; // gross weekly sales7 private double commissionRate; // commission percentage89 // 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 constructor1718 // set commission rate19 public void setCommissionRate( double rate )20 {21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;22 } // end method setCommissionRate2324 // return commission rate25 public double getCommissionRate()26 {27 return commissionRate;28 } // end method getCommissionRate2930 // set gross sales amount31 public void setGrossSales( double sales )32 {33 grossSales = ( sales < 0.0 ) ? 0.0 : sales;34 } // end method setGrossSales3536 // return gross sales amount37 public double getGrossSales()38 {39 return grossSales;40 } // end method getGrossSales4142 // calculate earnings; implement interface Payable method not43 // implemented by superclass Employee44 45 {46 return getCommissionRate() * getGrossSales();47 } // end method getPaymentAmount4849 // return String representation of CommissionEmployee object50 public String toString()51 {52 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", 53 "commission employee", super.toString(), 54 "gross sales", getGrossSales(), 55 "commission rate", getCommissionRate() );56 } // end method toString57 } // end class CommissionEmployee

Fig. L 10.7 | CommissionEmployee.java.

/* write a method header to satisfy the Payable interface */

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

Chapter 10 Object-Oriented Programming: Polymorphism 33

1 // Lab Exercise 2: BasePlusCommissionEmployee.java2 // BasePlusCommissionEmployee class extends CommissionEmployee.34 public class BasePlusCommissionEmployee extends CommissionEmployee 5 {6 private double baseSalary; // base salary per week78 // six-argument constructor9 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 salary14 } // end six-argument BasePlusCommissionEmployee constructor1516 // set base salary17 public void setBaseSalary( double salary )18 {19 baseSalary = ( salary < 0.0 ) ? 0.0 : salary; // non-negative20 } // end method setBaseSalary2122 // return base salary23 public double getBaseSalary()24 {25 return baseSalary;26 } // end method getBaseSalary2728 // calculate earnings; override CommissionEmployee implementation of29 // interface Payable method30 31 {32 33 } // end method getPaymentAmount3435 // return String representation of BasePlusCommissionEmployee object36 public String toString()37 {38 return String.format( "%s %s; %s: $%,.2f", 39 "base-salaried", super.toString(), 40 "base salary", getBaseSalary() );41 } // end method toString 42 } // end class BasePlusCommissionEmployee

Fig. L 10.8 | BasePlusCommissionEmployee.java.

1 // Lab Exercise 2: PayableInterfaceTest.java2 // Tests interface Payable.34 public class PayableInterfaceTest 5 {6 public static void main( String args[] )7 {8 // create six-element Payable array9 Payable payableObjects[] = new Payable[ 6 ];

10

Fig. L 10.9 | PayableInterfaceTest.java. (Part 1 of 2.)

/* write a method header to satisfy the Payable interface */

/* calculate and return the BasePlusCommissionEmployee's earnings */

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

34 Object-Oriented Programming: Polymorphism Chapter 10

Solution

11 // populate array with objects that implement Payable12 payableObjects[ 0 ] = new Invoice( "01234", "seat", 2, 375.00 );13 payableObjects[ 1 ] = new Invoice( "56789", "tire", 4, 79.95 );14 payableObjects[ 2 ] = 15 new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );16 payableObjects[ 3 ] = 17 18 payableObjects[ 4 ] = 19 20 payableObjects[ 5 ] = 21 2223 System.out.println( 24 "Invoices and Employees processed polymorphically:\n" ); 2526 // generically process each element in array payableObjects27 for ( Payable currentPayable : payableObjects )28 {29 // output currentPayable and its appropriate payment amount30 System.out.printf( "%s \n", currentPayable.toString() ); 31 32 33 34 {35 36 37 } // end if3839 System.out.printf( "%s: $%,.2f\n\n",40 "payment due", currentPayable.getPaymentAmount() ); 41 } // end for42 } // end main43 } // end class PayableInterfaceTest

1 // Lab Exercise 2: HourlyEmployee.java2 // HourlyEmployee class extends Employee, which implements Payable.34 public class HourlyEmployee extends Employee 5 {6 private double wage; // wage per hour7 private double hours; // hours worked for week89 // 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 and store hourly wage15 setHours( hoursWorked ); // validate and store hours worked16 } // end five-argument HourlyEmployee constructor17

Fig. L 10.9 | PayableInterfaceTest.java. (Part 2 of 2.)

/* create an HourlyEmployee object */

/* create a CommissionEmployee object */

/* create a BasePlusCommissionEmployee object */

/* write code to determine whether currentPayable is a BasePlusCommissionEmployee object */

/* write code to give a raise */ /* write code to ouput results of the raise */

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

Chapter 10 Object-Oriented Programming: Polymorphism 35

18 // set wage19 public void setWage( double hourlyWage )20 {21 wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage;22 } // end method setWage2324 // return wage25 public double getWage()26 {27 return wage;28 } // end method getWage2930 // set hours worked31 public void setHours( double hoursWorked )32 {33 hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ?34 hoursWorked : 0.0;35 } // end method setHours3637 // return hours worked38 public double getHours()39 {40 return hours;41 } // end method getHours4243 // calculate earnings; implement interface Payable method not44 // implemented by superclass Employee45 public double getPaymentAmount()46 {47 if ( getHours() <= 40 ) // no overtime48 return getWage() * getHours();49 else50 return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5;51 } // end method getPaymentAmount5253 // return String representation of HourlyEmployee object54 public String toString()55 {56 return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f", 57 super.toString(), "hourly wage", getWage(), 58 "hours worked", getHours() );59 } // end method toString60 } // end class HourlyEmployee

1 // Lab Exercise 2: CommissionEmployee.java2 // CommissionEmployee class extends Employee, which implements Payable.34 public class CommissionEmployee extends Employee 5 {6 private double grossSales; // gross weekly sales7 private double commissionRate; // commission percentage89 // five-argument constructor

10 public CommissionEmployee( String first, String last, String ssn, 11 double sales, double rate )12 {

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

36 Object-Oriented Programming: Polymorphism Chapter 10

13 super( first, last, ssn );14 setGrossSales( sales );15 setCommissionRate( rate );16 } // end five-argument CommissionEmployee constructor1718 // set commission rate19 public void setCommissionRate( double rate )20 {21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;22 } // end method setCommissionRate2324 // return commission rate25 public double getCommissionRate()26 {27 return commissionRate;28 } // end method getCommissionRate2930 // set gross sales amount31 public void setGrossSales( double sales )32 {33 grossSales = ( sales < 0.0 ) ? 0.0 : sales;34 } // end method setGrossSales3536 // return gross sales amount37 public double getGrossSales()38 {39 return grossSales;40 } // end method getGrossSales4142 // calculate earnings; implement interface Payable method not43 // implemented by superclass Employee44 public double getPaymentAmount()45 {46 return getCommissionRate() * getGrossSales();47 } // end method getPaymentAmount4849 // return String representation of CommissionEmployee object50 public String toString()51 {52 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", 53 "commission employee", super.toString(), 54 "gross sales", getGrossSales(), 55 "commission rate", getCommissionRate() );56 } // end method toString57 } // end class CommissionEmployee

1 // Lab Exercise 2: BasePlusCommissionEmployee.java2 // BasePlusCommissionEmployee class extends CommissionEmployee.34 public class BasePlusCommissionEmployee extends CommissionEmployee 5 {6 private double baseSalary; // base salary per week78 // six-argument constructor9 public BasePlusCommissionEmployee( String first, String last,

10 String ssn, double sales, double rate, double salary )11 {

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

Chapter 10 Object-Oriented Programming: Polymorphism 37

12 super( first, last, ssn, sales, rate );13 setBaseSalary( salary ); // validate and store base salary14 } // end six-argument BasePlusCommissionEmployee constructor1516 // set base salary17 public void setBaseSalary( double salary )18 {19 baseSalary = ( salary < 0.0 ) ? 0.0 : salary; // non-negative20 } // end method setBaseSalary2122 // return base salary23 public double getBaseSalary()24 {25 return baseSalary;26 } // end method getBaseSalary2728 // calculate earnings; override CommissionEmployee implementation of29 // interface Payable method30 public double getPaymentAmount()31 {32 return getBaseSalary() + super.getPaymentAmount();33 } // end method getPaymentAmount3435 // return String representation of BasePlusCommissionEmployee object36 public String toString()37 {38 return String.format( "%s %s; %s: $%,.2f", 39 "base-salaried", super.toString(), 40 "base salary", getBaseSalary() );41 } // end method toString 42 } // end class BasePlusCommissionEmployee

1 // Lab Exercise 2: PayableInterfaceTest.java2 // Tests interface Payable.34 public class PayableInterfaceTest 5 {6 public static void main( String args[] )7 {8 // create six-element Payable array9 Payable payableObjects[] = new Payable[ 6 ];

10 11 // populate array with objects that implement Payable12 payableObjects[ 0 ] = new Invoice( "01234", "seat", 2, 375.00 );13 payableObjects[ 1 ] = new Invoice( "56789", "tire", 4, 79.95 );14 payableObjects[ 2 ] = 15 new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );16 payableObjects[ 3 ] = 17 new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 );18 payableObjects[ 4 ] = 19 new CommissionEmployee( 20 "Sue", "Jones", "333-33-3333", 10000, .06 );21 payableObjects[ 5 ] = 22 new BasePlusCommissionEmployee( 23 "Bob", "Lewis", "444-44-4444", 5000, .04, 300 );24

Lab Exercises Name:

Lab Exercise 2 — Accounts Payable System Modification

38 Object-Oriented Programming: Polymorphism Chapter 10

Problem-Solving Tips1. Every class that implements interface Payable must declare a method called getPaymentAmount.

2. Class BasePlusCommissionEmployee must use its superclass’s getPaymentAmount method along with itsown base salary to calculate its total earnings.

3. Use the instanceof operator in PayableInterfaceTest to determine whether each object is a Base-PlusCommissionEmployee object.

4. If you have any questions as you proceed, ask your lab instructor for assistance.

Follow-Up Question and Activity1. Discuss the benefits and disadvantages of extending an abstract class vs. implementing an interface.

A benefit of an abstract class is that you can declare the instance variables and methods that are requiredby all classes in a hierarchy. Subclasses can then enhance the existing instance variables and methods inheritedfrom the abstract class and override existing methods as necessary. This reduces the amount of code that mustbe written to create each new class in the hierarchy. This benefit of abstract classes is a disadvantage of inter-faces, which are not allowed to provide any method implementations or instance variables. Thus, any class thatimplements an interface must define all the instance variables and methods necessary to properly satisfy therequirements of the interface.

A benefit of interfaces is that any class can implement an interface such that objects of that class can then beprocessed in a polymorphic program that uses variables of the interface type. This is particularly useful forextending existing systems.

A disadvantage of abstract classes (and classes in general) is that a class can extend only one other class at atime. However, a class can implement multiple interfaces.

25 System.out.println( 26 "Invoices and Employees processed polymorphically:\n" ); 2728 // generically process each element in array payableObjects29 for ( Payable currentPayable : payableObjects )30 {31 // output currentPayable and its appropriate payment amount32 System.out.printf( "%s \n", currentPayable.toString() ); 33 34 if ( currentPayable instanceof BasePlusCommissionEmployee )35 {36 // downcast Payable reference to 37 // BasePlusCommissionEmployee reference38 BasePlusCommissionEmployee employee = 39 ( BasePlusCommissionEmployee ) currentPayable;4041 double oldBaseSalary = employee.getBaseSalary();42 employee.setBaseSalary( 1.10 * oldBaseSalary );43 System.out.printf( 44 "new base salary with 10%% increase is: $%,.2f\n",45 employee.getBaseSalary() );46 } // end if4748 System.out.printf( "%s: $%,.2f\n\n",49 "payment due", currentPayable.getPaymentAmount() ); 50 } // end for51 } // end main52 } // end class PayableInterfaceTest

Lab Exercises Name:

Debugging

Chapter 10 Object-Oriented Programming: Polymorphism 39

Name: Date:

Section:

Debugging

The program in this section does not compile. Fix all the syntax errors so that the program will compile success-fully. Once the program compiles, execute the program, and compare the output with the sample output; theneliminate any logic errors that may exist. The sample output demonstrates what the program’s output should beonce the program’s code is corrected. The source code is available at www.pearsonhighered.com/deitel.

Sample Output

Broken Code

Point: [7, 11]Circle: Center = [22, 8]; Radius = 3.500000Cylinder: Center = [10, 10]; Radius = 3.300000; Height = 10.000000

Point: [7, 11]Area = 0.00Volume = 0.00

Circle: Center = [22, 8]; Radius = 3.500000Area = 38.48Volume = 0.00

Cylinder: Center = [10, 10]; Radius = 3.300000; Height = 10.000000Area = 275.77Volume = 342.12

1 // Shape.java2 // Definition of interface Shape34 public interface Shape 5 {6 public abstract String getName(); // return shape name7 } // end interface Shape

1 // Point.java2 // Definition of class Point34 public class Point implements Shape5 {6 protected int x, y; // coordinates of the Point78 // no-argument constructor9 public Point()

10 { 11 setPoint( 0, 0 ); 12 }

Lab Exercises Name:

Debugging

40 Object-Oriented Programming: Polymorphism Chapter 10

1314 // constructor15 public Point( int xCoordinate, int yCoordinate ) 16 { 17 setPoint( xCoordinate, yCoordinate ); 18 }1920 // Set x and y coordinates of Point21 public void setPoint( int xCoordinate, int yCoordinate )22 {23 x = xCoordinate;24 y = yCoordinate;25 }2627 // get x coordinate28 public int getX() 29 { 30 return x; 31 }3233 // get y coordinate34 public int getY() 35 { 36 return y; 37 }3839 // convert point into String representation40 public String toString() 41 { 42 return String.format( "[%d, %d]", x, y );43 }4445 // calculate area 46 public double area() 47 {48 return 0.0; 49 }5051 // calculate volume52 public double volume() 53 {54 return 0.0;55 }5657 // return shape name 58 public String getName() 59 { 60 return "Point"; 61 }62 } // end class Point

1 // Circle.java2 // Definition of class Circle34 public class Circle extends Point 5 {6 protected double radius;

Lab Exercises Name:

Debugging

Chapter 10 Object-Oriented Programming: Polymorphism 41

78 // no-argument constructor9 public Circle()

10 {11 // implicit call to superclass constructor here12 setRadius( 0 ); 13 }1415 // constructor16 public Circle( double circleRadius, int xCoordinate, int yCoordinate )17 {18 super( xCoordinate, yCoordinate ); // call superclass constructor1920 setRadius( circleRadius ); 21 }2223 // set radius of Circle24 public void setRadius( double circleRadius )25 { 26 radius = ( circleRadius >= 0 ? circleRadius : 0 ); 27 }2829 // get radius of Circle30 public double getRadius() 31 { 32 return radius; 33 }3435 // calculate area of Circle36 public double area() 37 { 38 return Math.PI * radius * radius; 39 }4041 // convert Circle to a String represention42 public String toString()43 { 44 return String.format( "Center = %s; Radius = %f", 45 super.toString(), radius ); 46 }4748 // return shape name49 public String getName()50 { 51 return "Circle"; 52 }53 } // end class Circle

1 // Cylinder.java2 // Definition of class Cylinder.34 public class Cylinder extends Circle5 {6 protected double height; // height of Cylinder7

Lab Exercises Name:

Debugging

42 Object-Oriented Programming: Polymorphism Chapter 10

8 // no-argument constructor9 public Cylinder()

10 {11 // implicit call to superclass constructor here12 setHeight( 0 );13 }1415 // constructor16 public Cylinder( double cylinderHeight, double cylinderRadius,17 int xCoordinate, int yCoordinate )18 {19 // call superclass constructor20 super( cylinderRadius, xCoordinate, yCoordinate );2122 setHeight( cylinderHeight );23 }2425 // set height of Cylinder26 public void setHeight( double cylinderHeight )27 { 28 height = ( cylinderHeight >= 0 ? cylinderHeight : 0 ); 29 }30 31 // get height of Cylinder32 public double getHeight() 33 {34 return height; 35 }3637 // calculate area of Cylinder (i.e., surface area)38 public double area()39 {40 return 2 * super.area() + 2 * Math.PI * radius * height;41 }42 43 // calculate volume of Cylinder44 public double volume() 45 { 46 return super.area() * height; 47 }4849 // convert Cylinder to a String representation50 public String toString()51 {52 return String.format( "%s; Height = %f", 53 super.toString(), height ); 54 }5556 // return shape name57 public String getName() 58 {59 return "Cylinder"; 60 }61 } // end class Cylinder

Lab Exercises Name:

Debugging

Chapter 10 Object-Oriented Programming: Polymorphism 43

Solution

1 // Test.java2 // Test Point, Circle, Cylinder hierarchy with interface Shape.34 public class Test5 {6 // test Shape hierarchy7 public static void main( String args[] )8 {9 // create shapes

10 Point point = new Point( 7, 11 ); 11 Circle circle = new Circle( 3.5, 22, 8 ); 12 Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );1314 Cylinder arrayOfShapes[] = new Cylinder[ 3 ]; // create Shape array1516 // aim arrayOfShapes[ 0 ] at subclass Point object17 arrayOfShapes[ 0 ] = ( Cylinder ) point;1819 // aim arrayOfShapes[ 1 ] at subclass Circle object20 arrayOfShapes[ 1 ] = ( Cylinder ) circle;2122 // aim arrayOfShapes[ 2 ] at subclass Cylinder object23 arrayOfShapes[ 2 ] = ( Cylinder ) cylinder; 2425 // get name and String representation of each shape26 System.out.printf( "%s: %s\n%s: %s\n%s: %s\n", point.getName(), 27 point, circle.getName(), circle, cylinder.getName(), cylinder );2829 // get name, area and volume of each shape in arrayOfShapes30 for ( Shape shape : arrayOfShapes ) 31 {32 System.out.printf( "\n\n%s: %s\nArea = %.2f\nVolume = %.2f\n",33 shape.getName(), shape, shape.area(), shape.volume() );34 } // end for35 } // end main36 } // end class Test

1 // Shape.java2 // Definition of interface Shape34 public interface Shape 5 {6 public abstract double area(); // calculate area7 public abstract double volume(); // calculate volume8 public abstract String getName(); // return shape name9 } // end interface Shape

1 // Point.java2 // Definition of class Point34 public class Point implements Shape5 {6 protected int x, y; // coordinates of the Point

Lab Exercises Name:

Debugging

44 Object-Oriented Programming: Polymorphism Chapter 10

78 // no-argument constructor9 public Point()

10 { 11 setPoint( 0, 0 ); 12 }1314 // constructor15 public Point( int xCoordinate, int yCoordinate ) 16 { 17 setPoint( xCoordinate, yCoordinate ); 18 }1920 // Set x and y coordinates of Point21 public void setPoint( int xCoordinate, int yCoordinate )22 {23 x = xCoordinate;24 y = yCoordinate;25 }2627 // get x coordinate28 public int getX() 29 { 30 return x; 31 }3233 // get y coordinate34 public int getY() 35 { 36 return y; 37 }3839 // convert point into String representation40 public String toString() 41 { 42 return String.format( "[%d, %d]", x, y );43 }4445 // calculate area 46 public double area() 47 {48 return 0.0; 49 }5051 // calculate volume52 public double volume() 53 {54 return 0.0;55 }5657 // return shape name 58 public String getName() 59 { 60 return "Point"; 61 }62 } // end class Point

Lab Exercises Name:

Debugging

Chapter 10 Object-Oriented Programming: Polymorphism 45

1 // Circle.java2 // Definition of class Circle34 public class Circle extends Point 5 {6 protected double radius;78 // no-argument constructor9 public Circle()

10 {11 // implicit call to superclass constructor here12 setRadius( 0 ); 13 }1415 // constructor16 public Circle( double circleRadius, int xCoordinate, int yCoordinate )17 {18 super( xCoordinate, yCoordinate ); // call superclass constructor1920 setRadius( circleRadius ); 21 }2223 // set radius of Circle24 public void setRadius( double circleRadius )25 { 26 radius = ( circleRadius >= 0 ? circleRadius : 0 ); 27 }2829 // get radius of Circle30 public double getRadius() 31 { 32 return radius; 33 }3435 // calculate area of Circle36 public double area() 37 { 38 return Math.PI * radius * radius; 39 }4041 // convert Circle to a String represention42 public String toString()43 { 44 return String.format( "Center = %s; Radius = %f", 45 super.toString(), radius ); 46 }4748 // return shape name49 public String getName()50 { 51 return "Circle"; 52 }53 } // end class Circle

Lab Exercises Name:

Debugging

46 Object-Oriented Programming: Polymorphism Chapter 10

1 // Cylinder.java2 // Definition of class Cylinder.34 public class Cylinder extends Circle5 {6 protected double height; // height of Cylinder7 8 // no-argument constructor9 public Cylinder()

10 {11 // implicit call to superclass constructor here12 setHeight( 0 );13 }1415 // constructor16 public Cylinder( double cylinderHeight, double cylinderRadius,17 int xCoordinate, int yCoordinate )18 {19 // call superclass constructor20 super( cylinderRadius, xCoordinate, yCoordinate );2122 setHeight( cylinderHeight );23 }2425 // set height of Cylinder26 public void setHeight( double cylinderHeight )27 { 28 height = ( cylinderHeight >= 0 ? cylinderHeight : 0 ); 29 }30 31 // get height of Cylinder32 public double getHeight() 33 {34 return height; 35 }3637 // calculate area of Cylinder (i.e., surface area)38 public double area()39 {40 return 2 * super.area() + 2 * Math.PI * radius * height;41 }42 43 // calculate volume of Cylinder44 public double volume() 45 { 46 return super.area() * height; 47 }4849 // convert Cylinder to a String representation50 public String toString()51 {52 return String.format( "%s; Height = %f", 53 super.toString(), height ); 54 }5556 // return shape name57 public String getName() 58 {

Lab Exercises Name:

Debugging

Chapter 10 Object-Oriented Programming: Polymorphism 47

List of Errors• Shape.java: The Shape interface must declare public abstract methods area and volume.• Test.java, line 14: The array should be of type Shape so that the array elements can refer to Point,

Circle and Cylinder objects for polymorphic processing.• Test.java, line 17: Once the array is changed to type Shape, it is not necessary to cast point to a dif-

ferent type—a Point object can always be assigned to a Shape variable based on the hierarchy definedin this exercise.

• Test.java, line 20: Once the array is changed to type Shape, it is not necessary to cast circle to a dif-ferent type—a Circle object can always be assigned to a Shape variable based on the hierarchy definedin this exercise.

• Test.java, line 23: The cast operation is unnecessary—a Cylinder object can always be assigned to aShape variable based on the hierarchy defined in this exercise.

59 return "Cylinder"; 60 }61 } // end class Cylinder

1 // Test.java2 // Test Point, Circle, Cylinder hierarchy with interface Shape.34 public class Test5 {6 // test Shape hierarchy7 public static void main( String args[] )8 {9 // create shapes

10 Point point = new Point( 7, 11 ); 11 Circle circle = new Circle( 3.5, 22, 8 ); 12 Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );1314 Shape arrayOfShapes[] = new Shape[ 3 ]; // create Shape array1516 // aim arrayOfShapes[ 0 ] at subclass Point object17 arrayOfShapes[ 0 ] = point;1819 // aim arrayOfShapes[ 1 ] at subclass Circle object20 arrayOfShapes[ 1 ] = circle;2122 // aim arrayOfShapes[ 2 ] at subclass Cylinder object23 arrayOfShapes[ 2 ] = cylinder; 2425 // get name and String representation of each shape26 System.out.printf( "%s: %s\n%s: %s\n%s: %s\n", point.getName(), 27 point, circle.getName(), circle, cylinder.getName(), cylinder );2829 // get name, area and volume of each shape in arrayOfShapes30 for ( Shape shape : arrayOfShapes ) 31 {32 System.out.printf( "\n\n%s: %s\nArea = %.2f\nVolume = %.2f\n",33 shape.getName(), shape, shape.area(), shape.volume() );34 } // end for35 } // end main36 } // end class Test

Chapter 10 Object-Oriented Programming: Polymorphism 49

Postlab Activities

Name: Date:

Section:

Coding Exercises

These coding exercises reinforce the lessons learned in the lab and provide additional programming experienceoutside the classroom and laboratory environment. They serve as a review after you have successfully completedthe Prelab Activities and Lab Exercises.

For each of the following problems, write a program or a program segment that performs the specified 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 writean accessor method getName for obtaining its value.

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

1 // Shape.java2 // Shape class declaration.34 public abstract class Shape5 {6 } // end class Shape

1 // Shape.java2 // Shape class declaration.34 public abstract class Shape5 {6 protected String shapeName;78 public String getName()9 {

10 return shapeName;11 }12 } // end class Shape

1 // Shape.java2 // Shape class declaration.34 public abstract class Shape5 {6 protected String shapeName;78 // abstract getArea method must be implemented by concrete subclasses9 public abstract double getArea();

10 11 public String getName()12 {13 return shapeName;14 }15 } // end class Shape

Postlab Activities Name:

Coding Exercises

50 Object-Oriented Programming: Polymorphism Chapter 10

4. Define a class Square that inherits from class Shape from Coding Exercise 3; it should contain an instancevariable side, which represents the length of a side of the square. Provide a constructor that takes one argu-ment representing the side of the square and sets the side variable. Ensure that the side is greater than orequal 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.

1 // Square.java2 // Definition of class Square.34 public class Square extends Shape5 {6 private double side;78 // constructor9 public Square( double s )

10 {11 side = ( s < 0 ? 0 : s );12 shapeName = "Square";13 }14 } // end class Square

1 // Square.java2 // Definition of class Square.34 public class Square extends Shape5 {6 private double side;78 // constructor9 public Square( double s )

10 {11 side = ( s < 0 ? 0 : s );12 shapeName = "Square";13 }1415 // return the area of a Square16 public double getArea()17 {18 return side * side;19 }20 } // end class Square

Postlab Activities Name:

Coding Exercises

Chapter 10 Object-Oriented Programming: Polymorphism 51

6. Define a class Rectangle that inherits from class Shape of Coding Exercise 3. The new class should containinstance variables length and width. Provide a constructor that takes two arguments representing the lengthand 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.

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

1 // Rectangle.java2 // Rectangle class declaration.34 public class Rectangle extends Shape5 {6 private double length, width;78 // constructor 9 public Rectangle( double s1, double s2 )

10 {11 length = ( s1 < 0 ? 0 : s1 );12 width = ( s2 < 0 ? 0 : s2 );13 shapeName = "Rectangle";14 }15 } // end class Rectangle

1 // Rectangle.java2 // Rectangle class declaration.34 public class Rectangle extends Shape5 {6 private double length, width;78 // constructor 9 public Rectangle( double s1, double s2 )

10 {11 length = ( s1 < 0 ? 0 : s1 );12 width = ( s2 < 0 ? 0 : s2 );13 shapeName = "Rectangle";14 }1516 // return the area of a Rectangle17 public double getArea()18 {19 return length * width;20 }21 } // end class Rectangle

Postlab Activities Name:

Coding Exercises

52 Object-Oriented Programming: Polymorphism Chapter 10

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 programshould polymorphically compute and display the areas of both objects. Allow a user to enter the values forthe side of the square and the length and width of the rectangle.

1 // TestArea.java2 import java.util.Scanner;34 public class TestArea 5 {6 public static void main( String args[] )7 {8 Scanner input = new Scanner( System.in );9

10 System.out.print( "Input the side of the square: " );11 double side = input.nextDouble();1213 System.out.print( "Input the length of the rectangle: " );14 double length = input.nextDouble();1516 System.out.print( "Input the width of the rectangle: " );17 double width = input.nextDouble();1819 Shape arrayOfShapes[] = new Shape[ 2 ];20 arrayOfShapes[ 0 ] = new Square( side );21 arrayOfShapes[ 1 ] = new Rectangle( length, width );2223 for ( Shape shape : arrayOfShapes )24 System.out.printf( "The %s has an area of %.2f\n", shape.getName(),25 shape.getArea() );26 } // end main27 } // end class TestArea

Input the side of the square: 10.5Input the length of the rectangle: 2.5Input the width of the rectangle: 3.5The Square has an area of 110.25The Rectangle has an area of 8.75

Postlab Activities Name:

Programming Challenges

Chapter 10 Object-Oriented Programming: Polymorphism 53

Name: Date:

Section:

Programming Challenges

The Programming Challenges are more involved than the Coding Exercises and may require a significant amountof time to complete. Write a Java program for each of the problems in this section. The answers to these problemsare available at www.pearsonhighered.com/deitel. Pseudocode, hints or sample outputs are provided for eachproblem to aid you in your programming.

1. (Payroll System Modification) Modify the payroll system of Figs. 10.4–10.9 to include private instance vari-able birthDate in class Employee. Use class Date of Fig. 8.7 to represent an employee’s birthday. Add getmethods to class Date and replace method toDateString with method toString. Assume that payroll is pro-cessed once per month. Create an array of Employee variables to store references to the various employeeobjects. In a loop, calculate the payroll for each Employee (polymorphically), and add a $100.00 bonus tothe person’s payroll amount if the current month is the month in which the Employee’s birthday occurs.

Hint:• Your output should appear as follows:

Date object constructor for date 6/15/1944Date object constructor for date 12/29/1960Date object constructor for date 9/8/1954Date object constructor for date 3/2/1965Employees processed individually:

salaried employee: John Smithsocial security number: 111-11-1111birth date: 6/15/1944weekly salary: $800.00earned: $800.00

hourly employee: Karen Pricesocial security number: 222-22-2222birth date: 12/29/1960hourly wage: $16.75; hours worked: 40.00earned: $670.00

commission employee: Sue Jonessocial security number: 333-33-3333birth date: 9/8/1954gross sales: $10,000.00; commission rate: 0.06earned: $600.00

base-salaried commission employee: Bob Lewissocial security number: 444-44-4444birth date: 3/2/1965gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00earned: $500.00

Enter the current month (1 - 12): 3

(continued next page...)

Postlab Activities Name:

Programming Challenges

54 Object-Oriented Programming: Polymorphism Chapter 10

Solution

Employees processed polymorphically:

salaried employee: John Smithsocial security number: 111-11-1111birth date: 6/15/1944weekly salary: $800.00earned $800.00

hourly employee: Karen Pricesocial security number: 222-22-2222birth date: 12/29/1960hourly wage: $16.75; hours worked: 40.00earned $670.00

commission employee: Sue Jonessocial security number: 333-33-3333birth date: 9/8/1954gross sales: $10,000.00; commission rate: 0.06earned $600.00

base-salaried commission employee: Bob Lewissocial security number: 444-44-4444birth date: 3/2/1965gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00new base salary with 10% increase is: $330.00earned $530.00 plus $100.00 birthday bonus

Employee 0 is a SalariedEmployeeEmployee 1 is a HourlyEmployeeEmployee 2 is a CommissionEmployeeEmployee 3 is a BasePlusCommissionEmployee

1 // Programming Challenge 1: Employee.java2 // Employee abstract superclass.34 public abstract class Employee 5 {6 private String firstName;7 private String lastName;8 private String socialSecurityNumber;9 private Date birthDate;

1011 // six-argument constructor12 public Employee( String first, String last, String ssn, 13 int month, int day, int year )14 {15 firstName = first;16 lastName = last;17 socialSecurityNumber = ssn;18 birthDate = new Date( month, day, year );19 } // end six-argument Employee constructor2021 // set first name22 public void setFirstName( String first )23 {24 firstName = first;

Postlab Activities Name:

Programming Challenges

Chapter 10 Object-Oriented Programming: Polymorphism 55

25 } // end method setFirstName2627 // return first name28 public String getFirstName()29 {30 return firstName;31 } // end method getFirstName3233 // set last name34 public void setLastName( String last )35 {36 lastName = last;37 } // end method setLastName3839 // return last name40 public String getLastName()41 {42 return lastName;43 } // end method getLastName4445 // set social security number46 public void setSocialSecurityNumber( String ssn )47 {48 socialSecurityNumber = ssn; // should validate49 } // end method setSocialSecurityNumber5051 // return social security number52 public String getSocialSecurityNumber()53 {54 return socialSecurityNumber;55 } // end method getSocialSecurityNumber5657 // set birth date58 public void setBirthDate( int month, int day, int year )59 {60 birthDate = new Date( month, day, year );61 } // end method setBirthDate6263 // return birth date64 public Date getBirthDate()65 {66 return birthDate;67 } // end method getBirthDate6869 // return String representation of Employee object70 public String toString()71 {72 return String.format( "%s %s\n%s: %s\n%s: %s", 73 getFirstName(), getLastName(), 74 "social security number", getSocialSecurityNumber(), 75 "birth date", getBirthDate() );76 } // end method toString7778 // abstract method overridden by subclasses79 public abstract double earnings();80 } // end abstract class Employee

Postlab Activities Name:

Programming Challenges

56 Object-Oriented Programming: Polymorphism Chapter 10

1 // Programming Challenge 1: Date.java 2 // Date class declaration with get methods added.34 public class Date 5 {6 private int month; // 1-127 private int day; // 1-31 based on month8 private int year; // any year9

10 // constructor: call checkMonth to confirm proper value for month; 11 // call checkDay to confirm proper value for day12 public Date( int theMonth, int theDay, int theYear )13 {14 month = checkMonth( theMonth ); // validate month15 year = theYear; // could validate year16 day = checkDay( theDay ); // validate day1718 System.out.printf( 19 "Date object constructor for date %s\n", toString() );20 } // end Date constructor2122 // utility method to confirm proper month value23 private int checkMonth( int testMonth )24 {25 if ( testMonth > 0 && testMonth <= 12 ) // validate month26 return testMonth;27 else // month is invalid 28 { 29 System.out.printf( "Invalid month (%d) set to 1.\n", testMonth );30 return 1; // maintain object in consistent state31 } // end else32 } // end method checkMonth3334 // utility method to confirm proper day value based on month and year35 private int checkDay( int testDay )36 {37 int daysPerMonth[] = 38 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };39 40 // check if day in range for month41 if ( testDay > 0 && testDay <= daysPerMonth[ month ] )42 return testDay;43 44 // check for leap year45 if ( month == 2 && testDay == 29 && ( year % 400 == 0 || 46 ( year % 4 == 0 && year % 100 != 0 ) ) )47 return testDay;48 49 System.out.printf( "Invalid day (%d) set to 1.\n", testDay );50 51 return 1; // maintain object in consistent state52 } // end method checkDay5354 // return day55 public int getDay()56 {57 return day;58 } // end method getDay

Postlab Activities Name:

Programming Challenges

Chapter 10 Object-Oriented Programming: Polymorphism 57

5960 // return month61 public int getMonth()62 {63 return month;64 } // end method getMonth6566 // return year67 public int getYear()68 {69 return year;70 } // end method getYear7172 // return a String of the form month/day/year73 public String toString()74 { 75 return String.format( "%d/%d/%d", month, day, year ); 76 } // end method toString77 } // end class Date

1 // Programming Challenge 1: SalariedEmployee.java2 // SalariedEmployee class derived from Employee.34 public class SalariedEmployee extends Employee 5 {6 private double weeklySalary;78 // seven-argument constructor9 public SalariedEmployee( String first, String last, String ssn,

10 int month, int day, int year, double salary )11 {12 super( first, last, ssn, month, day, year ); 13 setWeeklySalary( salary );14 } // end seven-argument SalariedEmployee constructor1516 // set salary17 public void setWeeklySalary( double salary )18 {19 weeklySalary = salary < 0.0 ? 0.0 : salary;20 } // end method setWeeklySalary2122 // return salary23 public double getWeeklySalary()24 {25 return weeklySalary;26 } // end method getWeeklySalary2728 // calculate earnings; override abstract method earnings in Employee29 public double earnings()30 {31 return getWeeklySalary();32 } // end method earnings3334 // return String representation of SalariedEmployee object35 public String toString()36 {

Postlab Activities Name:

Programming Challenges

58 Object-Oriented Programming: Polymorphism Chapter 10

37 return String.format( "salaried employee: %s\n%s: $%,.2f", 38 super.toString(), "weekly salary", getWeeklySalary() );39 } // end method toString 40 } // end class SalariedEmployee

1 // Programming Challenge 1: HourlyEmployee.java2 // HourlyEmployee class derived from Employee.34 public class HourlyEmployee extends Employee 5 {6 private double wage; // wage per hour7 private double hours; // hours worked for week89 // eight-argument constructor

10 public HourlyEmployee( String first, String last, String ssn, 11 int month, int day, int year,12 double hourlyWage, double hoursWorked )13 {14 super( first, last, ssn, month, day, year );15 setWage( hourlyWage );16 setHours( hoursWorked );17 } // end eight-argument HourlyEmployee constructor1819 // set wage20 public void setWage( double hourlyWage )21 {22 wage = hourlyWage < 0.0 ? 0.0 : hourlyWage;23 } // end method setWage2425 // return wage26 public double getWage()27 {28 return wage;29 } // end method getWage3031 // set hours worked32 public void setHours( double hoursWorked )33 {34 hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ?35 hoursWorked : 0.0;36 } // end method setHours3738 // return hours worked39 public double getHours()40 {41 return hours;42 } // end method getHours4344 // calculate earnings; override abstract method earnings in Employee45 public double earnings()46 {47 if ( getHours() <= 40 ) // no overtime48 return getWage() * getHours();49 else50 return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5;51 } // end method earnings52

Postlab Activities Name:

Programming Challenges

Chapter 10 Object-Oriented Programming: Polymorphism 59

53 // return String representation of HourlyEmployee object54 public String toString()55 {56 return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f", 57 super.toString(), "hourly wage", getWage(), 58 "hours worked", getHours() );59 } // end method toString60 } // end class HourlyEmployee

1 // Programming Challenge 1: CommissionEmployee.java2 // CommissionEmployee class derived from Employee.34 public class CommissionEmployee extends Employee 5 {6 private double grossSales; // gross weekly sales7 private double commissionRate; // commission percentage89 // eight-argument constructor

10 public CommissionEmployee( String first, String last, String ssn, 11 int month, int day, int year, double sales, double rate )12 {13 super( first, last, ssn, month, day, year );14 setGrossSales( sales );15 setCommissionRate( rate );16 } // end eight-argument CommissionEmployee constructor1718 // set commission rate19 public void setCommissionRate( double rate )20 {21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;22 } // end method setCommissionRate2324 // return commission rate25 public double getCommissionRate()26 {27 return commissionRate;28 } // end method getCommissionRate2930 // set gross sales amount31 public void setGrossSales( double sales )32 {33 grossSales = sales < 0.0 ? 0.0 : sales;34 } // end method setGrossSales3536 // return gross sales amount37 public double getGrossSales()38 {39 return grossSales;40 } // end method getGrossSales4142 // calculate earnings; override abstract method earnings in Employee43 public double earnings()44 {45 return getCommissionRate() * getGrossSales();46 } // end method earnings47

Postlab Activities Name:

Programming Challenges

60 Object-Oriented Programming: Polymorphism Chapter 10

48 // return String representation of CommissionEmployee object49 public String toString()50 {51 return String.format( "%s: %s\n%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

1 // Programming Challenge 1: BasePlusCommissionEmployee.java2 // BasePlusCommissionEmployee class derived from CommissionEmployee.34 public class BasePlusCommissionEmployee extends CommissionEmployee 5 {6 private double baseSalary; // base salary per week78 // nine-argument constructor9 public BasePlusCommissionEmployee( String first, String last,

10 String ssn, int month, int day, int year, 11 double sales, double rate, double salary )12 {13 super( first, last, ssn, month, day, year, sales, rate );14 setBaseSalary( salary );15 } // end nine-argument BasePlusCommissionEmployee constructor1617 // set base salary18 public void setBaseSalary( double salary )19 {20 baseSalary = salary < 0.0 ? 0.0 : salary; // non-negative21 } // end method setBaseSalary2223 // return base salary24 public double getBaseSalary()25 {26 return baseSalary;27 } // end method getBaseSalary2829 // calculate earnings; override method earnings in CommissionEmployee30 public double earnings()31 {32 return getBaseSalary() + super.earnings();33 } // end method earnings3435 // return String representation of BasePlusCommissionEmployee object36 public String toString()37 {38 return String.format( "%s %s; %s: $%,.2f", 39 "base-salaried", super.toString(), 40 "base salary", getBaseSalary() );41 } // end method toString42 } // end class BasePlusCommissionEmployee

Postlab Activities Name:

Programming Challenges

Chapter 10 Object-Oriented Programming: Polymorphism 61

1 // Programming Challenge 1: PayrollSystemTest.java2 // Employee hierarchy test program.3 import java.util.Scanner; // program uses Scanner to obtain user input45 public class PayrollSystemTest 6 {7 public static void main( String args[] ) 8 {9 // create subclass objects

10 SalariedEmployee salariedEmployee = 11 new SalariedEmployee( 12 "John", "Smith", "111-11-1111", 6, 15, 1944, 800.00 );13 HourlyEmployee hourlyEmployee = 14 new HourlyEmployee( 15 "Karen", "Price", "222-22-2222", 12, 29, 1960, 16.75, 40 );16 CommissionEmployee commissionEmployee = 17 new CommissionEmployee( 18 "Sue", "Jones", "333-33-3333", 9, 8, 1954, 10000, .06 );19 BasePlusCommissionEmployee basePlusCommissionEmployee = 20 new BasePlusCommissionEmployee( 21 "Bob", "Lewis", "444-44-4444", 3, 2, 1965, 5000, .04, 300 );2223 System.out.println( "Employees processed individually:\n" );2425 System.out.printf( "%s\n%s: $%,.2f\n\n", 26 salariedEmployee, "earned", salariedEmployee.earnings() );27 System.out.printf( "%s\n%s: $%,.2f\n\n",28 hourlyEmployee, "earned", hourlyEmployee.earnings() );29 System.out.printf( "%s\n%s: $%,.2f\n\n",30 commissionEmployee, "earned", commissionEmployee.earnings() );31 System.out.printf( "%s\n%s: $%,.2f\n\n", 32 basePlusCommissionEmployee, 33 "earned", basePlusCommissionEmployee.earnings() );3435 // create four-element Employee array36 Employee employees[] = new Employee[ 4 ]; 3738 // initialize array with Employees39 employees[ 0 ] = salariedEmployee;40 employees[ 1 ] = hourlyEmployee;41 employees[ 2 ] = commissionEmployee; 42 employees[ 3 ] = basePlusCommissionEmployee;4344 Scanner input = new Scanner( System.in ); // to get current month45 int currentMonth;4647 // get and validate current month48 do49 {50 System.out.print( "Enter the current month (1 - 12): " );51 currentMonth = input.nextInt();52 System.out.println();53 } while ( ( currentMonth < 1 ) || ( currentMonth > 12 ) );5455 System.out.println( "Employees processed polymorphically:\n" );56

Postlab Activities Name:

Programming Challenges

62 Object-Oriented Programming: Polymorphism Chapter 10

57 // generically process each element in array employees58 for ( Employee currentEmployee : employees ) 59 {60 System.out.println( currentEmployee ); // invokes toString6162 // determine whether element is a BasePlusCommissionEmployee63 if ( currentEmployee instanceof BasePlusCommissionEmployee ) 64 {65 // downcast Employee reference to 66 // BasePlusCommissionEmployee reference67 BasePlusCommissionEmployee employee = 68 ( BasePlusCommissionEmployee ) currentEmployee;6970 double oldBaseSalary = employee.getBaseSalary();71 employee.setBaseSalary( 1.10 * oldBaseSalary );72 System.out.printf( 73 "new base salary with 10%% increase is: $%,.2f\n",74 employee.getBaseSalary() );75 } // end if7677 // if month of employee's birthday, add $100 to salary78 if ( currentMonth == currentEmployee.getBirthDate().getMonth() )79 System.out.printf(80 "earned $%,.2f %s\n\n", currentEmployee.earnings(), 81 "plus $100.00 birthday bonus" );82 else83 System.out.printf( 84 "earned $%,.2f\n\n", currentEmployee.earnings() );85 } // end for8687 // get type name of each object in employees array88 for ( int j = 0; j < employees.length; j++ )89 System.out.printf( "Employee %d is a %s\n", j, 90 employees[ j ].getClass().getName() ); 91 } // end main92 } // end class PayrollSystemTest

Postlab Activities Name:

Programming Challenges

Chapter 10 Object-Oriented Programming: Polymorphism 63

2. (Shape Hierarchy) Implement the Shape hierarchy shown in Fig. 9.3 of Java How to Program. Each TwoDi-mensionalShape should contain method getArea to calculate the area of the two-dimensional shape. EachThreeDimensionalShape should have methods getArea and getVolume to calculate the surface area and vol-ume, respectively, of the three-dimensional shape. Create a program that uses an array of Shape referencesto objects of each concrete class in the hierarchy. The program should print a text description of the objectto which each array element refers. Also, in the loop that processes all the shapes in the array, determinewhether each shape is a TwoDimensionalShape or a ThreeDimensionalShape. If a shape is a TwoDimension-alShape, display its area. If a shape is a ThreeDimensionalShape, display its area and volume.

Hint:• Your output should appear as follows:

Solution

Circle: [22, 88] radius: 4Circle's area is 50

Square: [71, 96] side: 10Square's area is 100

Sphere: [8, 89] radius: 2Sphere's area is 50Sphere's volume is 33

Cube: [79, 61] side: 8Cube's area is 384Cube's volume is 512

1 // Programming Challenge 2: Shape.java2 // Definition of class Shape.34 public abstract class Shape 5 {6 private int x; // x coordinate7 private int y; // y coordinate89 // two-argument constructor

10 public Shape( int x, int y )11 {12 this.x = x;13 this.y = y;14 } // end two-argument Shape constructor1516 // set x coordinate17 public void setX( int x )18 {19 this.x = x;20 } // end method setX2122 // set y coordinate23 public void setY( int y )24 {25 this.y = y;26 } // end method setY

Postlab Activities Name:

Programming Challenges

64 Object-Oriented Programming: Polymorphism Chapter 10

2728 // get x coordinate29 public int getX()30 {31 return x;32 } // end method getX3334 // get y coordinate35 public int getY()36 {37 return y;38 } // end method getY3940 // return String representation of Shape object41 public String toString()42 {43 return String.format( "(%d, %d)", getX(), getY() );44 }4546 // abstract methods47 public abstract String getName();48 } // end class Shape

1 // Programming Challenge 2: TwoDimensionalShape.java2 // Definition of class TwoDimensionalShape.34 public abstract class TwoDimensionalShape extends Shape 5 {6 private int dimension1;7 private int dimension2;89 // four-argument constructor

10 public TwoDimensionalShape( int x, int y, int d1, int d2 )11 {12 super( x, y );13 dimension1 = d1;14 dimension2 = d2;15 } // end four-argument TwoDimensionalShape constructor1617 // set methods18 public void setDimension1( int d )19 {20 dimension1 = d;21 } // end method setDimension12223 public void setDimension2( int d )24 {25 dimension2 = d;26 } // end method setDimension22728 // get methods29 public int getDimension1()30 {31 return dimension1;32 } // end method getDimension133

Postlab Activities Name:

Programming Challenges

Chapter 10 Object-Oriented Programming: Polymorphism 65

34 public int getDimension2()35 {36 return dimension2;37 } // end method getDimension23839 // abstract method40 public abstract int getArea();41 } // end class TwoDimensionalShape

1 // Programming Challenge 2: Circle.java2 // Definition of class Circle.34 public class Circle extends TwoDimensionalShape 5 {6 // three-argument constructor7 public Circle( int x, int y, int radius )8 {9 super( x, y, radius, radius );

10 } // end three-argument Circle constructor1112 // overridden methods13 public String getName()14 {15 return "Circle";16 } // end method getName1718 public int getArea()19 {20 return ( int ) 21 ( Math.PI * getRadius() * getRadius() );22 } // end method getArea2324 // set method25 public void setRadius( int radius )26 {27 setDimension1( radius );28 setDimension2( radius );29 } // end method setRadius3031 // get method32 public int getRadius()33 {34 return getDimension1();35 } // end method getRadius36 37 public String toString()38 {39 return String.format( "%s %s: %d\n", 40 super.toString(), "radius", getRadius() );41 } // end method toString42 } // end class Circle

Postlab Activities Name:

Programming Challenges

66 Object-Oriented Programming: Polymorphism Chapter 10

1 // Programming Challenge 2: Square.java2 // Definition of class Square.34 public class Square extends TwoDimensionalShape 5 {6 // three-argument constructor7 public Square( int x, int y, int side )8 {9 super( x, y, side, side );

10 } // end three-argument Square constructor1112 // overridden methods13 public String getName()14 {15 return "Square";16 } // end method getName1718 public int getArea()19 {20 return getSide() * getSide();21 } // end method getArea2223 // set method24 public void setSide( int side )25 {26 setDimension1( side );27 setDimension2( side );28 } // end method setSide2930 // get method31 public int getSide()32 {33 return getDimension1();34 } // end method getSide35 36 public String toString()37 {38 return String.format( "%s %s: %d\n", 39 super.toString(), "side", getSide() );40 } // end method toString41 } // end class Square

1 // Programming Challenge 2: ThreeDimensionalShape.java2 // Definition of class ThreeDimensionalShape.34 public abstract class ThreeDimensionalShape extends Shape 5 {6 private int dimension1;7 private int dimension2;8 private int dimension3;9

10 // five-argument constructor11 public ThreeDimensionalShape(12 int x, int y, int d1, int d2, int d3 )13 {14 super( x, y );15 dimension1 = d1;

Postlab Activities Name:

Programming Challenges

Chapter 10 Object-Oriented Programming: Polymorphism 67

16 dimension2 = d2;17 dimension3 = d3;18 } // end five-argument ThreeDimensionalShape constructor1920 // set methods21 public void setDimension1( int d )22 {23 dimension1 = d;24 } // end method setDimension12526 public void setDimension2( int d )27 {28 dimension2 = d;29 } // end method setDimension23031 public void setDimension3( int d )32 {33 dimension3 = d;34 } // end method setDimension33536 // get methods37 public int getDimension1() 38 {39 return dimension1;40 } // end method getDimension14142 public int getDimension2()43 {44 return dimension2;45 } // end method getDimension24647 public int getDimension3()48 {49 return dimension3;50 } // end method getDimension35152 // abstract methods53 public abstract int getArea();54 public abstract int getVolume();55 } // end class ThreeDimensionalShape

1 // Programming Challenge 2: Sphere.java2 // Definition of class Sphere.34 public class Sphere extends ThreeDimensionalShape5 {6 // three-argument constructor7 public Sphere( int x, int y, int radius )8 {9 super( x, y, radius, radius, radius );

10 } // end three-argument Shape constructor1112 // overridden methods13 public String getName()14 {15 return "Sphere";16 } // end method getName

Postlab Activities Name:

Programming Challenges

68 Object-Oriented Programming: Polymorphism Chapter 10

1718 public int getArea()19 {20 return ( int ) ( 4 * Math.PI * getRadius() * getRadius() );21 } // end method getArea2223 public int getVolume()24 {25 return ( int ) ( 4.0 / 3.0 * Math.PI *26 getRadius() * getRadius() * getRadius() );27 } // end method getVolume2829 // set method30 public void setRadius( int radius )31 {32 setDimension1( radius );33 setDimension2( radius );34 setDimension3( radius );35 } // end method setRadius3637 // get method38 public int getRadius()39 {40 return getDimension1();41 } // end method getRadius42 43 public String toString()44 {45 return String.format( "%s %s: %d\n", 46 super.toString(), "radius", getRadius() );47 } // end method toString48 } // end class Sphere

1 // Programming Challenge 2: Cube.java2 // Definition of class Cube.34 public class Cube extends ThreeDimensionalShape 5 {6 // three-argument constructor7 public Cube( int x, int y, int side )8 {9 super( x, y, side, side, side );

10 } // end three-argument Cube constructor1112 // overridden methods13 public String getName()14 {15 return "Cube";16 } // end method getName1718 public int getArea()19 {20 return ( int ) ( 6 * getSide() * getSide() );21 } // end method getArea2223 public int getVolume()24 {

Postlab Activities Name:

Programming Challenges

Chapter 10 Object-Oriented Programming: Polymorphism 69

25 return ( int ) ( getSide() * getSide() * getSide() );26 } // end method getVolume2728 // set method29 public void setSide( int side )30 {31 setDimension1( side );32 setDimension2( side );33 setDimension3( side );34 } // end method setSide3536 // get method37 public int getSide()38 {39 return getDimension1();40 } // end method getSide41 42 public String toString()43 {44 return String.format( "%s %s: %d\n", 45 super.toString(), "side", getSide() );46 } // end method toString47 } // end class Cube

1 // Programming Challenge 2: ShapeTest.java2 // Program tests the Shape hierarchy.34 public class ShapeTest 5 {6 // create Shape objects and display their information7 public static void main( String args[] )8 {9 Shape shapes[] = new Shape[ 4 ];

10 shapes[ 0 ] = new Circle( 22, 88, 4 );11 shapes[ 1 ] = new Square( 71, 96, 10 );12 shapes[ 2 ] = new Sphere( 8, 89, 2 );13 shapes[ 3 ] = new Cube( 79, 61, 8 );1415 // call method print on all shapes16 for ( Shape currentShape : shapes ) 17 {18 System.out.printf( "%s: %s", 19 currentShape.getName(), currentShape );20 21 if ( currentShape instanceof TwoDimensionalShape )22 {23 TwoDimensionalShape twoDimensionalShape = 24 ( TwoDimensionalShape ) currentShape;2526 System.out.printf( "%s's area is %s\n", 27 currentShape.getName(), twoDimensionalShape.getArea() );28 } // end if29 30 if ( currentShape instanceof ThreeDimensionalShape )31 {32 ThreeDimensionalShape threeDimensionalShape =33 ( ThreeDimensionalShape ) currentShape;

Postlab Activities Name:

Programming Challenges

70 Object-Oriented Programming: Polymorphism Chapter 10

3435 System.out.printf( "%s's area is %s\n", 36 currentShape.getName(), threeDimensionalShape.getArea() );37 System.out.printf( "%s's volume is %s\n",38 currentShape.getName(),39 threeDimensionalShape.getVolume() );40 } // end if4142 System.out.println();43 } // end for44 } // end main45 } // end class ShapeTest