Description

10Object-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. Chapter 10 Object-Oriented Programming: Polymorphism 3 Assignment Checklist Name: Section: Date: Exercises Assigned: Circle assignments Date Due Prelab Activities Matching Fill in the Blank Short Answer Programming Output Correct the Code YES YES YES YES YES NO NO NO NO NO Lab Exercises Exercise 1 — Payroll System Modification Follow-Up Question and Activity YES 1 NO NO Exercise 2 — Accounts Payable System Modification YES Follow-Up Question and Activity Debugging 1 YES NO Postlab Activities Coding Exercises Programming Challenges 1, 2, 3, 4, 5, 6, 7, 8 1, 2 . answer the given questions. type-wrapper classes 5. concrete class 7. The questions are intended to test and reinforce your understanding of key concepts. polymorphism 8. c) Class method which returns the name of the class associated with the Class object. 3. l) . h) Indicates that a class will declare each method in an interface with the signature specified in the interface declaration. 2. 4. 12. 10. e) f) Uses superclass references to manipulate sets of subclass objects in a generic manner. abstract getClass method method keyword a) Can be used in place of an abstract class when there is no default implementation to inherit. interface k) A class that can be used to create objects. Returns an object that can be used to determine information about the object’s class. implements b) Indicates that a method cannot be overridden or that a class cannot be a superclass. 9. Classes in the java. downcasting 6. Term I J H L F K E D B C G A Description 1. write the letter for the description from the right column that best matches the term. the subclass must be declared abstract.lang package that are used to create objects containing values of primitive types. instanceof final getName d) An operator that returns true if its left operand (a variable of a reference type) has the is-a relationship with its right operand (a class or interface name). otherwise. 11.Chapter 10 Object-Oriented Programming: Polymorphism 5 Prelab Activities Matching Name: Section: Date: After reading Chapter 10 of Java How to Program: 8/e. method class abstract g) Cannot be instantiated. used primarily for inheritance. You may answer the questions before or during the lab. Casting a superclass reference to a subclass reference. i) j) Must be overridden in a subclass. For each term in the left column. . With polymorphism . it becomes possible to design and implement systems that are more extensible. 19. It is a syntax error if a class with one or more abstract methods is not explicitly declared abstract . Java executes the version of the method found in the subclass . 16. A(n) interface may contain a set of public abstract methods and/or public static final fields. 17. Although we cannot instantiate objects of abstract superclasses. .Chapter 10 Object-Oriented Programming: Polymorphism 7 Prelab Activities Fill in the Blank Name: Fill in the Blank Name: Section: Date: Fill in the blanks for each of the following statements: 13. 18. When a class implements an interface. The instanceof operator determines whether the type of the object to which its left operand refers has an is-a relationship with the type specified as its right operand. a class must specify that it implements the interface and must declare every method in the interface with the signatures specified in the interface declaration. 15. It is possible to assign a superclass reference to a subclass variable by downcasting the reference to the subclass type. 20. 14. it establishes an is-a relationship with the interface type. When a method is invoked through a superclass reference to a subclass object. 21. To use an interface. we can declare references of abstract superclass types. . aim for two or three sentences. Call method getClass on an object to obtain an object of type Class that represents the object’s type. a program can be designed to draw shapes rather than to draw rectangles. An abstract class cannot be used to create objects. 24. ovals and lines. . A concrete class can be used to create objects and declare variables. Polymorphism makes it possible to design and implement systems that are more easily extensible. Distinguish between an abstract class and a concrete class. Each shape object would know how to draw itself. or the class must be declared abstract to prevent this compilation error. Declaring a method final means that the method cannot be overridden in a subclass.. For example. Describe the concept of polymorphism. Then call the Class object’s getName method to get a String containing the class’s name. What happens when a class specifies that it implements an interface. 26. Programs can be written to process objects generically as one type. but does not provide declarations of all the methods in the interface? A compilation error occurs in this case. An abstract class can be used as a superclass and to declare variables that can store references to objects of the abstract class’s subclass. a concrete class can also be used as a superclass as long as it is not declared final. In addition. Declaring a class final means that it cannot be a superclass (i. a class cannot inherit from a final class). answer each of the given questions.Chapter 10 Object-Oriented Programming: Polymorphism 9 Prelab Activities Short Answer Name: Short Answer Name: Section: Date: In the space provided. 22. Your answers should be concise. Describe how to determine the class name of an object’s class. Every method in the interface must be implemented. Methods in a final class are implicitly final. and new classes can be added with little or no modifications to the generic part of the program. Define what it means to declare a method final and what it means to declare a class final. 25. 23.e. . ] Use the class definitions in Fig.1–Fig. String ssn ) { firstName = first.Chapter 10 Object-Oriented Programming: Polymorphism 11 Prelab Activities Programming Output Name: Programming Output Name: Section: Date: For each of the given program segments. public abstract class Employee { private String firstName. } // end method setLastName // return last name public String getLastName() { return lastName. [Note: Do not execute these programs on a computer.1 | Employee abstract superclass. } // end method getLastName Fig. lastName = last. } // end method getFirstName // set last name public void setLastName( String last ) { lastName = last.) .java // Employee abstract superclass. L 10. private String socialSecurityNumber. private String lastName. (Part 1 of 2. } // end three-argument Employee constructor // set first name public void setFirstName( String first ) { firstName = first.3 when answering Programming Output Exercises 27–30. String last. // three-argument constructor public Employee( String first. } // end method setFirstName // return first name public String getFirstName() { return firstName. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 // Employee. socialSecurityNumber = ssn. L 10. read the code and write the output in the space provided below each program. L 10. getFirstName().1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 abstract superclass. (Part 1 of 2.2 class derived from Employee. L 10. } // end method setWeeklySalary // return salary public double getWeeklySalary() { return weeklySalary. // no implementation here } // end abstract class Employee | Employee Fig. String last.) . (Part 2 of 2.0 : salary. } // end method getSocialSecurityNumber // return String representation of Employee object public String toString() { return String.0 ? 0. // should validate } // end method setSocialSecurityNumber // return social security number public String getSocialSecurityNumber() { return socialSecurityNumber. getSocialSecurityNumber() ). double salary ) { super( first. // validate and store salary } // end four-argument SalariedEmployee constructor // set salary public void setWeeklySalary( double salary ) { weeklySalary = salary < 0. // four-argument constructor public SalariedEmployee( String first. override abstract method earnings in Employee public double earnings() { | SalariedEmployee Fig. } // end method getWeeklySalary // calculate earnings. L 10.) // SalariedEmployee. ssn ).12 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Programming Output Name: 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 // set social security number public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn. } // end method toString // abstract method overridden by subclasses public abstract double earnings(). getLastName(). String ssn.java // SalariedEmployee class extends Employee. last. public class SalariedEmployee extends Employee { private double weeklySalary.format( "%s %s\nsocial security number: %s". // pass to Employee constructor setWeeklySalary( salary ). } // end method setCommissionRate // return commission rate public double getCommissionRate() { return commissionRate.0 ) ? rate : 0.0 : sales.0 && rate < 1. String last.format( "salaried employee: %s\n%s: $%.) // CommissionEmployee. } // end method setGrossSales // return gross sales amount public double getGrossSales() { return grossSales.Chapter 10 Object-Oriented Programming: Polymorphism 13 Prelab Activities Programming Output Name: 31 32 33 34 35 36 37 38 39 40 return getWeeklySalary().java // CommissionEmployee class extends Employee. } // end five-argument CommissionEmployee constructor // set commission rate public void setCommissionRate( double rate ) { commissionRate = ( rate > 0. super. setCommissionRate( rate ). getWeeklySalary() )..2f". public class CommissionEmployee extends Employee { private double grossSales. // gross weekly sales private double commissionRate.toString().3 | CommissionEmployee class derived from Employee. (Part 2 of 2. ssn ). L 10. "weekly salary". // commission percentage // five-argument constructor public CommissionEmployee( String first.) .0 ) ? 0. String ssn. double sales. (Part 1 of 2. } // end method getGrossSales Fig. } // end method getCommissionRate // set gross sales amount public void setGrossSales( double sales ) { grossSales = ( sales < 0. double rate ) { super( first. } // end method earnings // return String representation of SalariedEmployee object public String toString() { return String. last. L 10.0.2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 class derived from Employee. } // end method toString } // end class SalariedEmployee | SalariedEmployee Fig. setGrossSales( sales ). out. super. What is output by the following code segment? Assume that the code appears in the main method of an application.00. getGrossSales(). employee2 ).00. (Part 2 of 2. "gross sales".. "987-65-4321". System. "987-65-4321". "Bug". 0.00. "commission rate". CommissionEmployee employee2 = new CommissionEmployee( "Archie". . System. 1 2 3 4 5 Employee firstEmployee = new SalariedEmployee( "June". 0. } // end method toString } // end class CommissionEmployee | CommissionEmployee Fig. "123-45-6789". commission rate: 0. 15000. getCommissionRate() ). 15000. %s: %.000.00 Employee 2: commission employee: Archie Tic social security number: 987-65-4321 gross sales: $15.) 27. "commission employee". "Bug".toString().10 ).2f". 1 2 3 4 5 6 7 8 SalariedEmployee employee1 = new SalariedEmployee( "June".2f. Your answer: Employee 1: salaried employee: June Bug social security number: 123-45-6789 weekly salary: $1. "Tic". Employee secondEmployee = new CommissionEmployee( "Archie".printf( "Employee 2:\n%s\n\n".printf( "Employee 1:\n%s\n\n".10 28. } // end method earnings // return String representation of CommissionEmployee object public String toString() { return String. L 10.00 ). override abstract method earnings in Employee public double earnings() { return getCommissionRate() * getGrossSales(). What is output by the following code segment? Assume that the code appears in the main method of an application. "Tic". employee1 ). 1000.10 ).format( "%s: %s\n%s: $%.out.000. 1000.3 class derived from Employee.14 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Programming Output Name: 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // calculate earnings.00 ). "123-45-6789". 00 30. salaried ). System. Your answer: Employee 1: salaried employee: June Bug social security number: 123-45-6789 weekly salary: $1.main(Test.lang.00 Employee 2: commission employee: Archie Tic social security number: 987-65-4321 gross sales: $15.printf( "salaried:\n%s\n".out.printf( "Employee 2:\n%s\n\n".println( "commission:\n%s\n". 1 2 SalariedEmployee salaried = ( SalariedEmployee ) firstEmployee. firstEmployee ). secondEmployee ). Your answer: Although the cast in line 1 is allowed at compile time.out.Chapter 10 Object-Oriented Programming: Polymorphism 15 Prelab Activities Programming Output Name: 6 7 8 System.000.printf( "Employee 1:\n%s\n\n". commission ). System.000. 1 2 CommissionEmployee commission = ( CommissionEmployee ) firstEmployee.ClassCastException: SalariedEmployee at Test.00.java:17) . System. commission rate: 0.10 29. Exception in thread "main" java. this results in a ClassCastException at runtime because a SalariedEmployee is not a CommissionEmployee.out.out. Your answer: salaried: salaried employee: June Bug social security number: 123-45-6789 weekly salary: $1. What is output by the following code segment? Assume that the code follows the statements in Programming Output Exercise 28.000. What is output by the following code segment? Assume that the code follows the statements in Programming Output Exercise 29. . If the code does not contain an error.] For questions 31–33 assume the following definition of abstract class Employee. lastName = last. circle the error in the program and write the corrected code in the space provided after each problem. private String lastName.format( "%s %s".” [Note: There may be more than one error in a program segment. getLastName() ). } // end method toString // abstract method overridden by subclasses public abstract double earnings(). specify whether it is a logic error or a syntax error. public abstract class Employee { private String firstName. // three-argument constructor public Employee( String first. write “no error.Chapter 10 Object-Oriented Programming: Polymorphism 17 Prelab Activities Correct the Code Name: Correct the Code Name: Section: Date: Determine if there is an error in each of the following program segments. } // end three-argument Employee constructor // return first name public String getFirstName() { return firstName. } // end method getFirstName // return last name public String getLastName() { return lastName. If there is an error. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Employee abstract superclass. String last ) { firstName = first. getFirstName(). } // end method getLastName // return String representation of Employee object public String toString() { return String. // no implementation here } // end abstract class Employee . 18 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Correct the Code Name: 31. The following concrete class should inherit from abstract class Employee. A TipWorker is paid by the hour plus their tips for the week. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // TipWorker.java public final class TipWorker extends Employee { private double wage; // wage per hour private double hours; // hours worked for week private double tips; // tips for the week public TipWorker( String first, String last, double wagePerHour, double hoursWorked, double tipsEarned ) { super( first, last ); // call superclass constructor setWage ( wagePerHour ); setHours( hoursWorked ); setTips( tipsEarned ); } // set the wage public void setWage( double wagePerHour ) { wage = ( wagePerHour < 0 ? 0 : wagePerHour ); } // set the hours worked public void setHours( double hoursWorked ) { hours = ( hoursWorked >= 0 && hoursWorked < 168 ? hoursWorked : 0 ); } // set the tips public void setTips( double tipsEarned ) { tips = ( tipsEarned < 0 ? 0 : tipsEarned ); } } // end class TipWorker Your answer: Class TipWorker did not implement abstract method earnings that was inherited from class Employee. The class must implement this method to be a concrete class. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // TipWorker.java public final class TipWorker extends Employee { private double wage; // wage per hour private double hours; // hours worked for week private double tips; // tips for the week public TipWorker( String first, String last, double wagePerHour, double hoursWorked, double tipsEarned ) { super( first, last ); // call superclass constructor setWage ( wagePerHour ); setHours( hoursWorked ); setTips( tipsEarned ); } Chapter 10 Object-Oriented Programming: Polymorphism 19 Prelab Activities Correct the Code Name: 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 // set the wage public void setWage( double wagePerHour ) { wage = ( wagePerHour < 0 ? 0 : wagePerHour ); } // set the hours worked public void setHours( double hoursWorked ) { hours = ( hoursWorked >= 0 && hoursWorked < 168 ? hoursWorked : 0 ); } // set the tips public void setTips( double tipsEarned ) { tips = ( tipsEarned < 0 ? 0 : tipsEarned ); } // get the TipWorker's pay public double earnings() { return ( wage * hours ) + tips; } } // end class TipWorker 32. The following code should define method toString of class TipWorker in Correct the Code Exercise 31. 1 2 3 4 5 6 7 // return a string representation of a TipWorker public String toString() { return String.format( "Tip worker: %s\n%s: $%,.2f; %s: %.2f; %s: $%,.2f\n", toString(), "hourly wage", wage, "hours worked", hours, "tips earned", tips ); } Your answer: The call to toString in line 5 should call the superclass’s toString; otherwise, this causes infinite recursion. 1 2 3 4 5 6 7 // return a string representation of a TipWorker public String toString() { return String.format( "Tip worker: %s\n%s: $%,.2f; %s: %.2f; %s: $%,.2f\n", super.toString() , "hourly wage", wage, "hours worked", hours, "tips earned", tips ); } 20 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Correct the Code Name: 33. The following code should input information about five TipWorkers from the user and then print that information and all the TipWorkers’ calculated earnings. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Test2.java import java.util.Scanner; public class Test2 { public static void main( String args[] ) { Employee employee[]; Scanner input = new Scanner( System.in ); for ( int i = 0; i < employee.length; i++ ) { System.out.print( "Input first name: " ); String firstName = input.nextLine(); System.out.print( "Input last name: " ); String lastName = input.nextLine(); System.out.print( "Input hours worked: " ); double hours = input.nextDouble(); System.out.print( "Input tips earned: " ); double tips = input.nextDouble(); employee[ i ] = new Employee( firstName, lastName, 2.63, hours, tips ); System.out.printf( "%s %s earned $%.2f\n", employee[ i ].getFirstName(), employee[ i ].getLastName(), employee[ i ].earnings() ); input.nextLine(); // clear any remaining characters in the input stream } // end for } // end main } // end class Test2 Your answer: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // Test2.java import java.util.Scanner; public class Test2 { public static void main( String args[] ) { Employee employee[] = new Employee[ 5 ]; Scanner input = new Scanner( System.in ); for ( int i = 0; i < employee.length; i++ ) { System.out.print( "\nInput first name: " ); String firstName = input.nextLine(); System.out.print( "Input last name: " ); String lastName = input.nextLine(); employee[ i ]. System.earnings() ).nextDouble().2f\n".print( "Input tips earned: " ).out.Chapter 10 Object-Oriented Programming: Polymorphism 21 Prelab Activities Correct the Code Name: 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 System. double tips = input. input. double hours = input. hours. // clear any remaining characters in the input stream } // end for } // end main } // end class Test2 .print( "Input hours worked: " ). 2.out. employee[ i ] = new TipWorker( firstName.getLastName(). lastName.nextLine(). System.printf( "%s %s earned $%. employee[ i ].nextDouble().63. employee[ i ].out. tips ).getFirstName(). . Lab Objectives This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: 8/e. Compare your output with the sample output provided. Create an array of Employee variables to store references to objects of each concrete class in the new Employee hierarchy. display its string representation and earnings. .pearsonhighered. The problem is divided into six parts: 1. Understanding polymorphism. Using the problem-solving tips as a guide. Lab Objectives 2.4–Fig. For each Employee. Class PieceWorker should contain private instance variables wage (to store the employee’s wage per piece) and pieces (to store the number of pieces produced). you will practice: • • • Creating a new class and adding it to an existing class hierarchy.4–10. L 10. Sample Output 4. In this lab. Compile and execute the program. with one or more key lines of code replaced with comments. Description of the Problem 3. Program Template (Fig. Read the problem description and examine the sample output. Problem-Solving Tips 6. Provide a concrete implementation of method earnings in class PieceWorker that calculates the employee’s earnings by multiplying the number of pieces produced by the wage per piece. L 10.9 to include an additional Employee subclass PieceWorker that represents an employee whose pay is based on the number of pieces of merchandise produced. replace the /* */ comments with Java code.5) 5. The source code for the template is available at www. The follow-up question and activity also will give you practice: Description of the Problem (Payroll System Modification) Modify the payroll system of Figs. Then answer the follow-up questions.com/deitel. Follow-Up Question and Activity The program template represents a complete working Java program. then study the template code. Using the updated class hierarchy in a polymorphic application. 10.Chapter 10 Object-Oriented Programming: Polymorphism 23 Lab Exercises Lab Exercise 1 — Payroll System Modification Name: Section: Date: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. String last.00 commission employee: Sue Jones social security number: 333-33-3333 gross sales: $10.4 | PieceWorker.04. commission rate: 0.24 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Name: Lab Exercise 1 — Payroll System Modification Sample Output Employees processed polymorphically: salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800. int piecesProduced ) { /* write code to initialize a PieceWorker */ } // end five-argument PieceWorker constructor // set wage /* write a set method that validates and sets the PieceWorker's wage */ // return wage /* write a get method that returns the PieceWorker's wage */ // set pieces produced /* write a set method that validates and sets the number of pieces produced */ Fig.000. hours worked: 40.00 earned $500. base salary: $300.00 $670.java // PieceWorker class extends Employee.java.25. public class PieceWorker extends Employee { /* declare instance variable wage */ /* declare instance variable pieces */ // five-argument constructor public PieceWorker( String first.00. L 10.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 gross sales: $5.) .00.06 earned $600. String ssn.75.00 Program Template 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Lab Exercise 1: PieceWorker.00 earned $800.00 hourly social hourly earned employee: Karen Price security number: 222-22-2222 wage: $16.000. double wagePerPiece. commission rate: 0. pieces produced: 400 earned $900.00 piece worker: Rick Bridges social security number: 555-55-5555 wage per piece: $2. (Part 1 of 2. println( currentEmployee ).java Fig.. "111-11-1111".04. "Lewis". "333-33-3333". employees[ 3 ] = new BasePlusCommissionEmployee( "Bob". "222-22-2222".5 | . override abstract method earnings in Employee public double earnings() { /* write code to return the earnings for a PieceWorker */ } // end method earnings // return String representation of PieceWorker object public String toString() { /* write code to return a string representation of a PieceWorker */ } // end method toString } // end class PieceWorker PieceWorker. .75. 10000.printf( "earned $%. Fig. // invokes toString System.out. public class PayrollSystemTest { public static void main( String args[] ) { // create five-element Employee array Employee employees[] = new Employee[ 5 ]. /* create a PieceWoker object and assign it to employees[ 4 ] */ System. .out. "Price". employees[ 1 ] = new HourlyEmployee( "Karen".00 ). 40 ). L 10. L 10. 16. } // end for } // end main } // end class PayrollSystemTest PayrollSystemTest.06 ).java.Chapter 10 Object-Oriented Programming: Polymorphism 25 Lab Exercises Name: Lab Exercise 1 — Payroll System Modification 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 // return pieces produced /* write a get method that returns the number of pieces produced */ // calculate earnings.2f\n\n". "444-44-4444". // generically process each element in array employees for ( Employee currentEmployee : employees ) { System.earnings() ). 300 ). "Jones".4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 (Part 2 of 2.out.java // Employee hierarchy test program.println( "Employees processed polymorphically:\n" ). "Smith". employees[ 2 ] = new CommissionEmployee( "Sue". 5000. // initialize array with Employees employees[ 0 ] = new SalariedEmployee( "John".) // Lab Exercise 1: PayrollSystemTest. 800. currentEmployee. public class PieceWorker extends Employee { private double wage.format( "%s: %s\n%s: $%. getPieces() ). } // end method toString } // end class PieceWorker . super. last. } // end method setWage // return wage public double getWage() { return wage. } // end method getWage // set pieces produced public void setPieces( int piecesProduced ) { pieces = ( piecesProduced < 0 ) ? 0 : piecesProduced. "pieces produced". String last.toString(). } // end method getPieces // calculate earnings.0 : wagePerPiece. } // end method setPieces // return pieces produced public int getPieces() { return pieces. setWage( wagePerPiece ).2f. int piecesProduced ) { super( first. // wage per piece private int pieces. // validate and store pieces produced } // end five-argument PieceWorker constructor // set wage public void setWage( double wagePerPiece ) { wage = ( wagePerPiece < 0. "piece worker". getWage(). // pieces of merchandise produced in week // five-argument constructor public PieceWorker( String first. ssn ). // validate and store wage per piece setPieces( piecesProduced ).. "wage per piece". %s: %d". override abstract method earnings in Employee public double earnings() { return getPieces() * getWage().0 ) ? 0. } // end method earnings // return String representation of PieceWorker object public String toString() { return String. String ssn. double wagePerPiece.26 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Name: Lab Exercise 1 — Payroll System Modification Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 // Lab Exercise 1: PieceWorker // PieceWorker class extends Employee. 5000. Also. "Bridges". ask your lab instructor for assistance. 16. Explain the line of code in your PayrollSystemTest’s main method that calls method earnings. Place this logic in the set method for the wage variable.earnings() ). "Lewis". . "444-44-4444". "333-33-3333". Place this logic in the set method for the pieces variable.2f\n\n".04. The main method must explicitly create a new employees array. Every element of array employees refers to an object that is an Employee.out. "Smith". Since class Employee declares an abstract earnings method. 300 ). 800. "222-22-2222". "555-55-5555". "Price".. .println( currentEmployee ). 40 ). The wage should be greater than or equal to 0.06 ). "Jones". // initialize array with Employees employees[ 0 ] = new SalariedEmployee( "John". // generically process each element in array employees for ( Employee currentEmployee : employees ) { System. Follow-Up Question and Activity 1. 400 ). If you have any questions as you proceed. // invokes toString System. currentEmployee.out. employees[ 1 ] = new HourlyEmployee( "Karen". "111-11-1111". employees[ 2 ] = new CommissionEmployee( "Sue". it is guaranteed that the object to which currentEmployee refers during an iteration of the for statement will have an earnings method.25. . public class PayrollSystemTest { public static void main( String args[] ) { // create five-element Employee array Employee employees[] = new Employee[ 5 ].out. 2. PieceWorker object and assign it to an element of the 5. employees[ 3 ] = new BasePlusCommissionEmployee( "Bob". } // end for } // end main } // end class PayrollSystemTest Problem-Solving Tips 1.75. since objects can be created only from concrete classes. employees[ 4 ] = new PieceWorker( "Rick". 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. every concrete subclass of Employee must implement the earnings method.printf( "earned $%. 2. 10000.java // Employee hierarchy test program.println( "Employees processed polymorphically:\n" ). 4. The PieceWorker constructor should call the superclass Employee constructor to initialize the employee’s name. 3.00 ).Chapter 10 Object-Oriented Programming: Polymorphism 27 Lab Exercises Name: Lab Exercise 1 — Payroll System Modification 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Lab Exercise 1: PayrollSystemTest. The number of pieces produced should be greater than or equal to 0. System. . Then answer the follow-up question. Comparing interfaces and abstract classes. 10. If the object currently being processed is a BasePlusCommissionEmployee.5–10. . the application should increase the BasePlusCommissionEmployee’s base salary by 10%. L 10. 10.Chapter 10 Object-Oriented Programming: Polymorphism 29 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification Lab Exercise 2 — Accounts Payable System Modification Name: Section: Date: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. Complete the following steps to create the new application: a) Modify classes HourlyEmployee and CommissionEmployee to place them in the Payable hierarchy as subclasses of the version of Employee that implements Payable (Fig. In this lab you will practice: • • Provide additional polymorphic processing capabilities to an inheritance hierarchy by implementing an interface.pearsonhighered.com/deitel. we modify the accounts payable application of Figs.9) 5.11–10. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program. Using the problem-solving tips as a guide. 10. Compile and execute the program. [Hint: Change the name of method earnings to getPaymentAmount in each subclass so that the class satisfies its inherited contract with interface Payable.8). L 10.13).6–Fig. then study the template code. Program Template (Fig. with one or more key lines of code replaced with comments. the application should output the payment amount for each object.15 to include the complete functionality of the payroll application. Read the problem description and examine the sample output. Description of the Problem 3. The source code for the template is available at www. The application should still process two Invoice objects.] b) Modify class BasePlusCommissionEmployee such that it extends the version of class CommissionEmployee created in Part a. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: 8/e. Sample Output 4. but now should process one object of each of the four Employee subclasses (Figs. replace the /* */ comments with Java code. The problem is divided into six parts: 1. The follow-up question and activity will also give you practice: • Description of the Problem (Accounts Payable System Modification) In this exercise. Using the instanceof operator to determine whether a variable refers to an object that has an is-a relationship with a particular class. Lab Objectives 2. Compare your output with the sample output provided. Finally. increase its base salary by 10%.00 hourly employee: Karen Price social security number: 222-22-2222 hourly wage: $16.06 payment due: $600. if an object is a BasePlusCommissionEmployee.6 | HourlyEmployee. one one CommissionEmployee and one BasePlusCommissionEmployee.00 invoice: part number: 56789 (tire) quantity: 4 price per item: $79.000. which implements Payable. commission rate: 0. output the payment amount for each Payable object.java.00 payment due: $530. commission rate: 0.00 payment due: $800.75.00.95 payment due: $319.00.80 salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800. (Part 1 of 2. hours worked: 40. Modify Sample Output Invoices and Employees processed polymorphically: invoice: part number: 01234 (seat) quantity: 2 price per item: $375.000.) .30 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification c) to polymorphically process two Invoices.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 gross sales: $5.00 Program Template 1 2 3 4 5 6 7 8 // Lab Exercise 2: HourlyEmployee. Next. base salary: $300.java // HourlyEmployee class extends Employee.00 payment due: $670.04. First output a string representation of each Payable object. Finally. // wage per hour private double hours. one SalariedEmployee. PayableInterfaceTest HourlyEmployee. public class HourlyEmployee extends Employee { private double wage. // hours worked for week Fig. L 10.00 commission employee: Sue Jones social security number: 333-33-3333 gross sales: $10.00 new base salary with 10% increase is: $330.00 payment due: $750. String ssn. "hourly wage".) . getWage(). } // end method getHours // calculate earnings. } // end method getPaymentAmount // return String representation of HourlyEmployee object public String toString() { return String. } // end method toString } // end class HourlyEmployee HourlyEmployee. String last.toString().5.0. } // end method getWage // set hours worked public void setHours( double hoursWorked ) { hours = ( ( hoursWorked >= 0. %s: %. implement interface Payable method not // implemented by superclass Employee /* write a method header to satisfy the Payable interface */ { if ( getHours() <= 40 ) // no overtime return getWage() * getHours().0 ) ? 0.. } // end method setHours // return hours worked public double getHours() { return hours. super. ssn ).format( "hourly employee: %s\n%s: $%. // validate and store hours worked } // end five-argument HourlyEmployee constructor // set wage public void setWage( double hourlyWage ) { wage = ( hourlyWage < 0. double hoursWorked ) { super( first.Chapter 10 Object-Oriented Programming: Polymorphism 31 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 // five-argument constructor public HourlyEmployee( String first. else return 40 * getWage() + ( getHours() . last. Fig.0 ) && ( hoursWorked <= 168.2f.40 ) * getWage() * 1. "hours worked". L 10.0 ) ) ? hoursWorked : 0.java.6 | (Part 2 of 2. } // end method setWage // return wage public double getWage() { return wage. // validate and store hourly wage setHours( hoursWorked ).. double hourlyWage.0 : hourlyWage. setWage( hourlyWage ). getHours() ).2f". setCommissionRate( rate ). } // end method setGrossSales // return gross sales amount public double getGrossSales() { return grossSales. } // end method setCommissionRate // return commission rate public double getCommissionRate() { return commissionRate. super.32 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 // Lab Exercise 2: CommissionEmployee. %s: %. // commission percentage // five-argument constructor public CommissionEmployee( String first. getGrossSales().2f.toString(). which implements Payable.0 : sales. } // end method toString } // end class CommissionEmployee CommissionEmployee. "commission rate".0 ) ? rate : 0. Fig. getCommissionRate() ).format( "%s: %s\n%s: $%. double rate ) { super( first.java // CommissionEmployee class extends Employee. } // end method getPaymentAmount // return String representation of CommissionEmployee object public String toString() { return String.0 ) ? 0. "gross sales". } // end five-argument CommissionEmployee constructor // set commission rate public void setCommissionRate( double rate ) { commissionRate = ( rate > 0. } // end method getGrossSales // calculate earnings. } // end method getCommissionRate // set gross sales amount public void setGrossSales( double sales ) { grossSales = ( sales < 0. last. double sales.0 && rate < 1. String ssn. String last. setGrossSales( sales ).java.. ssn ).0. // gross weekly sales private double commissionRate.7 | . L 10.2f". "commission employee". implement interface Payable method not // implemented by superclass Employee /* write a method header to satisfy the Payable interface */ { return getCommissionRate() * getGrossSales(). public class CommissionEmployee extends Employee { private double grossSales. format( "%s %s.) . public class PayableInterfaceTest { public static void main( String args[] ) { // create six-element Payable array Payable payableObjects[] = new Payable[ 6 ]. double sales. "base salary".toString(). sales. setBaseSalary( salary ).2f".0 ) ? 0.8 | 1 2 3 4 5 6 7 8 9 10 // Lab Exercise 2: PayableInterfaceTest. double salary ) { super( first.java. override CommissionEmployee implementation of // interface Payable method /* write a method header to satisfy the Payable interface */ { /* calculate and return the BasePlusCommissionEmployee's earnings */ } // end method getPaymentAmount // return String representation of BasePlusCommissionEmployee object public String toString() { return String. } // end method toString } // end class BasePlusCommissionEmployee BasePlusCommissionEmployee. L 10. public class BasePlusCommissionEmployee extends CommissionEmployee { private double baseSalary.9 | PayableInterfaceTest.java. getBaseSalary() ). double rate. } // end method getBaseSalary // calculate earnings.. String ssn.java // BasePlusCommissionEmployee class extends CommissionEmployee. (Part 1 of 2. %s: $%. super. // non-negative } // end method setBaseSalary // return base salary public double getBaseSalary() { return baseSalary. // validate and store base salary } // end six-argument BasePlusCommissionEmployee constructor // set base salary public void setBaseSalary( double salary ) { baseSalary = ( salary < 0. ssn.0 : salary.java // Tests interface Payable. L 10.Chapter 10 Object-Oriented Programming: Polymorphism 33 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 // Lab Exercise 2: BasePlusCommissionEmployee. Fig. "base-salaried". rate ). Fig. last. String last. // base salary per week // six-argument constructor public BasePlusCommissionEmployee( String first. 79.printf( "%s \n". last. payableObjects[ 2 ] = new SalariedEmployee( "John". setWage( hourlyWage ).9 | (Part 2 of 2. "payment due". 4. double hoursWorked ) { super( first. 800. // hours worked for week // five-argument constructor public HourlyEmployee( String first.00 ). "tire". String ssn. // generically process each element in array payableObjects for ( Payable currentPayable : payableObjects ) { // output currentPayable and its appropriate payment amount System.println( "Invoices and Employees processed polymorphically:\n" ). "111-11-1111". 2. L 10.95 ). 375.) Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // Lab Exercise 2: HourlyEmployee. public class HourlyEmployee extends Employee { private double wage.getPaymentAmount() ).printf( "%s: $%. Fig. /* write code to determine whether currentPayable is a BasePlusCommissionEmployee object */ { /* write code to give a raise */ /* write code to ouput results of the raise */ } // end if System. } // end for } // end main } // end class PayableInterfaceTest PayableInterfaceTest. currentPayable. // validate and store hourly wage setHours( hoursWorked ). payableObjects[ 1 ] = new Invoice( "56789".out.out. "Smith".34 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 // populate array with objects that implement Payable payableObjects[ 0 ] = new Invoice( "01234". double hourlyWage.toString() ).java. // validate and store hours worked } // end five-argument HourlyEmployee constructor . ssn ).00 ).. String last. // wage per hour private double hours. "seat".2f\n\n".java // HourlyEmployee class extends Employee. which implements Payable. currentPayable.out. payableObjects[ 3 ] = /* create an HourlyEmployee object */ payableObjects[ 4 ] = /* create a CommissionEmployee object */ payableObjects[ 5 ] = /* create a BasePlusCommissionEmployee object */ System. getWage().2f.Chapter 10 Object-Oriented Programming: Polymorphism 35 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 // set wage public void setWage( double hourlyWage ) { wage = ( hourlyWage < 0. } // end method getPaymentAmount // return String representation of HourlyEmployee object public String toString() { return String. String ssn. else return 40 * getWage() + ( getHours() .40 ) * getWage() * 1. which implements Payable.0 ) && ( hoursWorked <= 168.0 ) ) ? hoursWorked : 0. %s: %. double rate ) { . String last..2f". super.0 : hourlyWage. } // end method setWage // return wage public double getWage() { return wage.0 ) ? 0. double sales.. "hourly wage". // gross weekly sales private double commissionRate. } // end method getHours // calculate earnings.5. getHours() ). } // end method getWage // set hours worked public void setHours( double hoursWorked ) { hours = ( ( hoursWorked >= 0.format( "hourly employee: %s\n%s: $%.java // CommissionEmployee class extends Employee.toString(). } // end method toString } // end class HourlyEmployee 1 2 3 4 5 6 7 8 9 10 11 12 // Lab Exercise 2: CommissionEmployee.0. // commission percentage // five-argument constructor public CommissionEmployee( String first. "hours worked". } // end method setHours // return hours worked public double getHours() { return hours. public class CommissionEmployee extends Employee { private double grossSales. implement interface Payable method not // implemented by superclass Employee public double getPaymentAmount() { if ( getHours() <= 40 ) // no overtime return getWage() * getHours(). implement interface Payable method not // implemented by superclass Employee public double getPaymentAmount() { return getCommissionRate() * getGrossSales().0. String ssn. ssn ). "commission employee". getGrossSales().java // BasePlusCommissionEmployee class extends CommissionEmployee. } // end method setCommissionRate // return commission rate public double getCommissionRate() { return commissionRate. } // end method getGrossSales // calculate earnings. double sales. } // end five-argument CommissionEmployee constructor // set commission rate public void setCommissionRate( double rate ) { commissionRate = ( rate > 0. last. double rate.0 && rate < 1.2f". double salary ) { . String last. setGrossSales( sales ).36 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 super( first..2f. %s: %. // base salary per week // six-argument constructor public BasePlusCommissionEmployee( String first. } // end method getCommissionRate // set gross sales amount public void setGrossSales( double sales ) { grossSales = ( sales < 0. "commission rate". public class BasePlusCommissionEmployee extends CommissionEmployee { private double baseSalary. setCommissionRate( rate ). getCommissionRate() ). } // end method toString } // end class CommissionEmployee 1 2 3 4 5 6 7 8 9 10 11 // Lab Exercise 2: BasePlusCommissionEmployee.format( "%s: %s\n%s: $%. } // end method setGrossSales // return gross sales amount public double getGrossSales() { return grossSales. "gross sales".0 : sales. } // end method getPaymentAmount // return String representation of CommissionEmployee object public String toString() { return String. super.toString().0 ) ? 0.0 ) ? rate : 0. 10000. "444-44-4444". rate ).getPaymentAmount().toString(). public class PayableInterfaceTest { public static void main( String args[] ) { // create six-element Payable array Payable payableObjects[] = new Payable[ 6 ]. // validate and store base salary } // end six-argument BasePlusCommissionEmployee constructor // set base salary public void setBaseSalary( double salary ) { baseSalary = ( salary < 0.75. "333-33-3333". "Lewis". .06 ). 375. 40 ). 79.2f". sales. last.00 ). payableObjects[ 3 ] = new HourlyEmployee( "Karen". getBaseSalary() ). "111-11-1111".00 ). "Jones". "Smith". "Price". payableObjects[ 1 ] = new Invoice( "56789". override CommissionEmployee implementation of // interface Payable method public double getPaymentAmount() { return getBaseSalary() + super. . "base salary".format( "%s %s.. } // end method getPaymentAmount // return String representation of BasePlusCommissionEmployee object public String toString() { return String. 2. ssn. 4. . 800. // populate array with objects that implement Payable payableObjects[ 0 ] = new Invoice( "01234".0 : salary.04. "seat". super. "222-22-2222". %s: $%. 300 ). } // end method getBaseSalary // calculate earnings. setBaseSalary( salary ). "base-salaried". 16. // non-negative } // end method setBaseSalary // return base salary public double getBaseSalary() { return baseSalary.Chapter 10 Object-Oriented Programming: Polymorphism 37 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 super( first.java // Tests interface Payable.0 ) ? 0. payableObjects[ 2 ] = new SalariedEmployee( "John". payableObjects[ 5 ] = new BasePlusCommissionEmployee( "Bob". 5000. } // end method toString } // end class BasePlusCommissionEmployee 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Lab Exercise 2: PayableInterfaceTest.95 ). payableObjects[ 4 ] = new CommissionEmployee( "Sue". "tire". Discuss the benefits and disadvantages of extending an abstract class vs.out. "payment due".out. This benefit of abstract classes is a disadvantage of interfaces.toString() ). employee. Class BasePlusCommissionEmployee must use its superclass’s getPaymentAmount method along with its own base salary to calculate its total earnings.. Every class that implements interface Payable must declare a method called getPaymentAmount. Subclasses can then enhance the existing instance variables and methods inherited from the abstract class and override existing methods as necessary. a class can implement multiple interfaces. currentPayable.printf( "%s: $%.setBaseSalary( 1. any class that implements an interface must define all the instance variables and methods necessary to properly satisfy the requirements of the interface. double oldBaseSalary = employee. This reduces the amount of code that must be written to create each new class in the hierarchy. // generically process each element in array payableObjects for ( Payable currentPayable : payableObjects ) { // output currentPayable and its appropriate payment amount System. Thus.printf( "new base salary with 10%% increase is: $%. Use the instanceof operator in PayableInterfaceTest to determine whether each object is a PlusCommissionEmployee object. If you have any questions as you proceed.getBaseSalary() ).38 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Name: Lab Exercise 2 — Accounts Payable System Modification 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 System. } // end if System. A benefit of interfaces is that any class can implement an interface such that objects of that class can then be processed in a polymorphic program that uses variables of the interface type.2f\n". 2. 3.out. System.printf( "%s \n". This is particularly useful for extending existing systems.10 * oldBaseSalary ).getBaseSalary(). . } // end for } // end main } // end class PayableInterfaceTest Problem-Solving Tips 1..2f\n\n". employee. However. A disadvantage of abstract classes (and classes in general) is that a class can extend only one other class at a time. if ( currentPayable instanceof BasePlusCommissionEmployee ) { // downcast Payable reference to // BasePlusCommissionEmployee reference BasePlusCommissionEmployee employee = ( BasePlusCommissionEmployee ) currentPayable.println( "Invoices and Employees processed polymorphically:\n" ). 4.out.getPaymentAmount() ). Base- Follow-Up Question and Activity 1. currentPayable. implementing an interface. which are not allowed to provide any method implementations or instance variables. A benefit of an abstract class is that you can declare the instance variables and methods that are required by all classes in a hierarchy. ask your lab instructor for assistance. The source code is available at www. Radius = 3. Radius = 3. Fix all the syntax errors so that the program will compile successfully.300000. Height = 10.500000 Cylinder: Center = [10. and compare the output with the sample output. Sample Output Point: [7.00 Volume = 0. 11] Circle: Center = [22.java // Definition of class Point public class Point implements Shape { protected int x. } . 11] Area = 0.pearsonhighered. // coordinates of the Point // no-argument constructor public Point() { setPoint( 0.Chapter 10 Object-Oriented Programming: Polymorphism 39 Lab Exercises Debugging Name: Debugging Name: Section: Date: The program in this section does not compile. 10]. 0 ). Once the program compiles.000000 Area = 275. // return shape name } // end interface Shape 1 2 3 4 5 6 7 8 9 10 11 12 // Point.java // Definition of interface Shape public interface Shape { public abstract String getName(). Height = 10.77 Volume = 342. Radius = 3.500000 Area = 38.12 Broken Code 1 2 3 4 5 6 7 // Shape. 8].com/deitel. 8]. The sample output demonstrates what the program’s output should be once the program’s code is corrected.00 Circle: Center = [22.00 Cylinder: Center = [10.000000 Point: [7. 10]. execute the program. then eliminate any logic errors that may exist.48 Volume = 0.300000. Radius = 3. y. 40 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Debugging Name: 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 // constructor public Point( int xCoordinate. . // get x coordinate public int getX() { return x.java // Definition of class Circle public class Circle extends Point { protected double radius. } // get y coordinate public int getY() { return y. } // calculate volume public double volume() { return 0.0. %d]". } // Set public { x = y = } x and y coordinates of Point void setPoint( int xCoordinate. } // calculate area public double area() { return 0. x.0. yCoordinate ). y ).format( "[%d. } // convert point into String representation public String toString() { return String. int yCoordinate ) { setPoint( xCoordinate. yCoordinate. } // return shape name public String getName() { return "Point". } } // end class Point 1 2 3 4 5 6 // Circle. int yCoordinate ) xCoordinate. } // constructor public Circle( double circleRadius.format( "Center = %s. super. Radius = %f". yCoordinate ). } // get radius of Circle public double getRadius() { return radius. // call superclass constructor setRadius( circleRadius ). public class Cylinder extends Circle { protected double height. int xCoordinate. } // calculate area of Circle public double area() { return Math.Chapter 10 Object-Oriented Programming: Polymorphism 41 Lab Exercises Debugging Name: 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 // no-argument constructor public Circle() { // implicit call to superclass constructor here setRadius( 0 ). radius ). int yCoordinate ) { super( xCoordinate.PI * radius * radius. // height of Cylinder . } // return shape name public String getName() { return "Circle". } // convert Circle to a String represention public String toString() { return String.toString(). } // set radius of Circle public void setRadius( double circleRadius ) { radius = ( circleRadius >= 0 ? circleRadius : 0 ).java // Definition of class Cylinder. } } // end class Circle 1 2 3 4 5 6 7 // Cylinder. } // convert Cylinder to a String representation public String toString() { return String. } // constructor public Cylinder( double cylinderHeight.area() * height.e. } // set height of Cylinder public void setHeight( double cylinderHeight ) { height = ( cylinderHeight >= 0 ? cylinderHeight : 0 ). int xCoordinate. setHeight( cylinderHeight ).42 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Debugging Name: 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 // no-argument constructor public Cylinder() { // implicit call to superclass constructor here setHeight( 0 ). double cylinderRadius. surface area) public double area() { return 2 * super. yCoordinate ). super. } // calculate volume of Cylinder public double volume() { return super.toString(). } // return shape name public String getName() { return "Cylinder". xCoordinate. height ). } // calculate area of Cylinder (i.PI * radius * height. } } // end class Cylinder . Height = %f"..area() + 2 * Math.format( "%s. int yCoordinate ) { // call superclass constructor super( cylinderRadius. } // get height of Cylinder public double getHeight() { return height. out. public class Test { // test Shape hierarchy public static void main( String args[] ) { // create shapes Point point = new Point( 7.2f\nVolume = %.java // Definition of class Point public class Point implements Shape { protected int x. point. cylinder ). area and volume of each shape in arrayOfShapes for ( Shape shape : arrayOfShapes ) { System. // aim arrayOfShapes[ 2 ] at subclass Cylinder object arrayOfShapes[ 2 ] = ( Cylinder ) cylinder. point. 22.5.getName(). 10 ). shape. // get name. y. // get name and String representation of each shape System.area(). circle. } // end for } // end main } // end class Test Solution 1 2 3 4 5 6 7 8 9 // Shape. Circle circle = new Circle( 3.getName(). Circle. // coordinates of the Point .getName(). Cylinder cylinder = new Cylinder( 10.java // Test Point.2f\n". // calculate area public abstract double volume().getName(). 11 ).3. // calculate volume public abstract String getName(). Cylinder hierarchy with interface Shape. Cylinder arrayOfShapes[] = new Cylinder[ 3 ].volume() ). circle. 3. // create Shape array // aim arrayOfShapes[ 0 ] at subclass Point object arrayOfShapes[ 0 ] = ( Cylinder ) point. 10. shape.printf( "\n\n%s: %s\nArea = %. shape. 8 ). cylinder. // aim arrayOfShapes[ 1 ] at subclass Circle object arrayOfShapes[ 1 ] = ( Cylinder ) circle.printf( "%s: %s\n%s: %s\n%s: %s\n".out. // return shape name } // end interface Shape 1 2 3 4 5 6 // Point.java // Definition of interface Shape public interface Shape { public abstract double area().Chapter 10 Object-Oriented Programming: Polymorphism 43 Lab Exercises Debugging Name: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 // Test. shape. } // calculate area public double area() { return 0. } // Set public { x = y = } x and y coordinates of Point void setPoint( int xCoordinate. yCoordinate.0. y ).0. } // constructor public Point( int xCoordinate. } // get y coordinate public int getY() { return y.44 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Debugging Name: 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 // no-argument constructor public Point() { setPoint( 0. 0 ). } // return shape name public String getName() { return "Point". int yCoordinate ) xCoordinate. yCoordinate ). } // convert point into String representation public String toString() { return String. // get x coordinate public int getX() { return x. } } // end class Point . x. } // calculate volume public double volume() { return 0. int yCoordinate ) { setPoint( xCoordinate.format( "[%d. %d]". radius ). super.java // Definition of class Circle public class Circle extends Point { protected double radius. // call superclass constructor setRadius( circleRadius ). } // calculate area of Circle public double area() { return Math.PI * radius * radius. } // return shape name public String getName() { return "Circle".Chapter 10 Object-Oriented Programming: Polymorphism 45 Lab Exercises Debugging Name: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 // Circle. Radius = %f". } // constructor public Circle( double circleRadius. yCoordinate ).toString(). } // set radius of Circle public void setRadius( double circleRadius ) { radius = ( circleRadius >= 0 ? circleRadius : 0 ). // no-argument constructor public Circle() { // implicit call to superclass constructor here setRadius( 0 ). } // get radius of Circle public double getRadius() { return radius. int xCoordinate. } } // end class Circle . } // convert Circle to a String represention public String toString() { return String.format( "Center = %s. int yCoordinate ) { super( xCoordinate. area() + 2 * Math. int yCoordinate ) { // call superclass constructor super( cylinderRadius. height ). super. } // constructor public Cylinder( double cylinderHeight. } // calculate volume of Cylinder public double volume() { return super.area() * height. surface area) public double area() { return 2 * super. // height of Cylinder // no-argument constructor public Cylinder() { // implicit call to superclass constructor here setHeight( 0 ). public class Cylinder extends Circle { protected double height.toString()..46 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Debugging Name: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 // Cylinder. } // convert Cylinder to a String representation public String toString() { return String. yCoordinate ).java // Definition of class Cylinder.format( "%s. xCoordinate. int xCoordinate. } // set height of Cylinder public void setHeight( double cylinderHeight ) { height = ( cylinderHeight >= 0 ? cylinderHeight : 0 ).PI * radius * height. } // return shape name public String getName() { . } // get height of Cylinder public double getHeight() { return height. double cylinderRadius.e. } // calculate area of Cylinder (i. setHeight( cylinderHeight ). Height = %f". it is not necessary to cast point to a different type—a Point object can always be assigned to a Shape variable based on the hierarchy defined in this exercise.2f\n".getName(). // aim arrayOfShapes[ 2 ] at subclass Cylinder object arrayOfShapes[ 2 ] = cylinder.printf( "\n\n%s: %s\nArea = %. cylinder ). line 23: The cast operation is unnecessary—a Cylinder object can always be assigned to a Shape variable based on the hierarchy defined in this exercise. shape. 22. 10 ).area(). Test. line 20: Once the array is changed to type Shape. line 14: The array should be of type Shape so that the array elements can refer to Point.volume() ). circle. circle. Shape arrayOfShapes[] = new Shape[ 3 ].5. point. public class Test { // test Shape hierarchy public static void main( String args[] ) { // create shapes Point point = new Point( 7. area and volume of each shape in arrayOfShapes for ( Shape shape : arrayOfShapes ) { System.java: • • . Circle and Cylinder objects for polymorphic processing. // aim arrayOfShapes[ 1 ] at subclass Circle object arrayOfShapes[ 1 ] = circle. shape. 11 ). line 17: Once the array is changed to type Shape. Circle.java.Chapter 10 Object-Oriented Programming: Polymorphism 47 Lab Exercises Debugging Name: 59 60 61 return "Cylinder".getName().out. Cylinder hierarchy with interface Shape. it is not necessary to cast circle to a different type—a Circle object can always be assigned to a Shape variable based on the hierarchy defined in this exercise.getName(). } // end for } // end main } // end class Test List of Errors • • • The Shape interface must declare public abstract methods area and volume. cylinder.java. Test. shape. Shape.2f\nVolume = %. Test.printf( "%s: %s\n%s: %s\n%s: %s\n".java // Test Point.out. // get name and String representation of each shape System. Circle circle = new Circle( 3. Test. // get name. Cylinder cylinder = new Cylinder( 10. 8 ). // create Shape array // aim arrayOfShapes[ 0 ] at subclass Point object arrayOfShapes[ 0 ] = point. 3. } } // end class Cylinder 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 // Test.3.java. shape. 10.getName(). point.java. . public String getName() { return shapeName. and write an accessor method getName for obtaining its value. public String getName() { return shapeName. In the class of Coding Exercise 2. write a program or a program segment that performs the specified action. In the class from Coding Exercise 1.Chapter 10 Object-Oriented Programming: Polymorphism 49 Postlab Activities Coding Exercises Name: Section: Date: These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. } } // end class Shape 3. public abstract class Shape { protected String shapeName. They serve as a review after you have successfully completed the Prelab Activities and Lab Exercises. Write an empty class declaration for an abstract class called Shape. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Shape. define an abstract method getArea that returns a double representation of a specific shape’s area. create a protected instance variable shapeName of type String. } } // end class Shape . 1 2 3 4 5 6 // Shape. public abstract class Shape { protected String shapeName. Subclasses of this class must implement getArea to calculate a specific shape’s area. // abstract getArea method must be implemented by concrete subclasses public abstract double getArea(). For each of the following problems. public abstract class Shape { } // end class Shape 2. 1 2 3 4 5 6 7 8 9 10 11 12 // Shape.java // Shape class declaration.java // Shape class declaration. 1.java // Shape class declaration. java // Definition of class Square. it should contain an instance variable side. public class Square extends Shape { private double side. shapeName = "Square". The Square class from Coding Exercise 4 should implement the getArea method of its abstract superclass. Provide a constructor that takes one argument representing the side of the square and sets the side variable. shapeName = "Square". public class Square extends Shape { private double side. // constructor public Square( double s ) { side = ( s < 0 ? 0 : s ). Define a class Square that inherits from class Shape from Coding Exercise 3. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Square. this implementation should compute the area of the square and return the result. Ensure that the side is greater than or equal to 0. which represents the length of a side of the square. } // return the area of a Square public double getArea() { return side * side. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // Square. } } // end class Square . // constructor public Square( double s ) { side = ( s < 0 ? 0 : s ). The constructor should set the inherited shapeName variable to the string "Square".50 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Coding Exercises Name: 4.java // Definition of class Square. } } // end class Square 5. Chapter 10 Object-Oriented Programming: Polymorphism 51 Postlab Activities Coding Exercises Name: 6. double s2 ) { length = ( s1 < 0 ? 0 : s1 ). Define a class Rectangle that inherits from class Shape of Coding Exercise 3. width = ( s2 < 0 ? 0 : s2 ). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Rectangle. shapeName = "Rectangle". 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Rectangle. } // return the area of a Rectangle public double getArea() { return length * width. width. // constructor public Rectangle( double s1. // constructor public Rectangle( double s1. The Rectangle class from Coding Exercise 6 should also implement the getArea method of its abstract superclass. Provide a constructor that takes two arguments representing the length and width of the rectangle. shapeName = "Rectangle". Ensure that the length and width are both greater than or equal to 0. The new class should contain instance variables length and width. } } // end class Rectangle . public class Rectangle extends Shape { private double length.java // Rectangle class declaration. width. sets the two variables and sets the inherited shapeName variable to the string "Rectangle". public class Rectangle extends Shape { private double length. double s2 ) { length = ( s1 < 0 ? 0 : s1 ).java // Rectangle class declaration. width = ( s2 < 0 ? 0 : s2 ). } } // end class Rectangle 7. this implementation should compute the area of the rectangle and return the result. System.5 Input the length of the rectangle: 2. double side = input. respectively. System.nextDouble().Scanner.print( "Input the side of the square: " ).print( "Input the length of the rectangle: " ). Write an application that tests the Square and Rectangle classes from Coding Exercises 5 and 7.5 The Square has an area of 110. Shape arrayOfShapes[] = new Shape[ 2 ]. arrayOfShapes[ 0 ] = new Square( side ).out. The program should polymorphically compute and display the areas of both objects.2f\n".out.75 .25 The Rectangle has an area of 8. double length = input.5 Input the width of the rectangle: 3.print( "Input the width of the rectangle: " ). arrayOfShapes[ 1 ] = new Rectangle( length.util.nextDouble(). public class TestArea { public static void main( String args[] ) { Scanner input = new Scanner( System.out. width ). Create an array of type Shape that holds an instance of Square and an instance of Rectangle. shape. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // TestArea.getName(). Allow a user to enter the values for the side of the square and the length and width of the rectangle.in ).52 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Coding Exercises Name: 8.out. double width = input. } // end main } // end class TestArea Input the side of the square: 10. System.nextDouble(). shape.getArea() ).printf( "The %s has an area of %. for ( Shape shape : arrayOfShapes ) System.java import java. commission rate: 0.00 earned: $800. Create an array of Employee variables to store references to the various employee objects.06 earned: $600.00 earned: $670. Pseudocode.00..00 earned: $500.pearsonhighered.) .00 hourly employee: Karen Price social security number: 222-22-2222 birth date: 12/29/1960 hourly wage: $16. commission rate: 0. 8. and add a $100. Use class Date of Fig.000.00 bonus to the person’s payroll amount if the current month is the month in which the Employee’s birthday occurs.00 commission employee: Sue Jones social security number: 333-33-3333 birth date: 9/8/1954 gross sales: $10. Assume that payroll is processed once per month..75. 1.000. base salary: $300. Add get methods to class Date and replace method toDateString with method toString.4–10. Write a Java program for each of the problems in this section. In a loop.04.Chapter 10 Object-Oriented Programming: Polymorphism 53 Postlab Activities Programming Challenges Name: Programming Challenges Name: Section: Date: The Programming Challenges are more involved than the Coding Exercises and may require a significant amount of time to complete.00 Enter the current month (1 . hints or sample outputs are provided for each problem to aid you in your programming. Hint: • Your output should appear as follows: Date object constructor for date 6/15/1944 Date object constructor for date 12/29/1960 Date object constructor for date 9/8/1954 Date object constructor for date 3/2/1965 Employees processed individually: salaried employee: John Smith social security number: 111-11-1111 birth date: 6/15/1944 weekly salary: $800. The answers to these problems are available at www.00.9 to include private instance variable birthDate in class Employee.12): 3 (continued next page.com/deitel. calculate the payroll for each Employee (polymorphically).7 to represent an employee’s birthday.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 birth date: 3/2/1965 gross sales: $5. hours worked: 40. (Payroll System Modification) Modify the payroll system of Figs. 10. 00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 birth date: 3/2/1965 gross sales: $5.54 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Name: Employees processed polymorphically: salaried employee: John Smith social security number: 111-11-1111 birth date: 6/15/1944 weekly salary: $800.04. int day. birthDate = new Date( month.java // Employee abstract superclass.06 earned $600.75. day.00 earned $530. lastName = last. hours worked: 40.00 commission employee: Sue Jones social security number: 333-33-3333 birth date: 9/8/1954 gross sales: $10. socialSecurityNumber = ssn.00 earned $800. String last. public abstract class Employee { private String firstName. // six-argument constructor public Employee( String first. String ssn. base salary: $300.00 birthday bonus Employee Employee Employee Employee 0 1 2 3 is is is is a a a a SalariedEmployee HourlyEmployee CommissionEmployee BasePlusCommissionEmployee Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Programming Challenge 1: Employee. int year ) { firstName = first. year ). private String lastName.00.00 plus $100.000. commission rate: 0. commission rate: 0. private String socialSecurityNumber. } // end six-argument Employee constructor // set first name public void setFirstName( String first ) { firstName = first.00 earned $670.00 new base salary with 10% increase is: $330.000. .00 hourly employee: Karen Price social security number: 222-22-2222 birth date: 12/29/1960 hourly wage: $16. private Date birthDate.00. int month. } // end method getLastName // set social security number public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn. } // end method getFirstName // set last name public void setLastName( String last ) { lastName = last. getFirstName(). int year ) { birthDate = new Date( month.Chapter 10 Object-Oriented Programming: Polymorphism 55 Postlab Activities Programming Challenges Name: 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 } // end method setFirstName // return first name public String getFirstName() { return firstName. } // end method getBirthDate // return String representation of Employee object public String toString() { return String.format( "%s %s\n%s: %s\n%s: %s". getLastName(). } // end method setLastName // return last name public String getLastName() { return lastName. int day. getBirthDate() ). } // end method getSocialSecurityNumber // set birth date public void setBirthDate( int month. } // end method toString // abstract method overridden by subclasses public abstract double earnings(). } // end abstract class Employee . "social security number". } // end method setBirthDate // return birth date public Date getBirthDate() { return birthDate. year ). getSocialSecurityNumber(). "birth date". day. // should validate } // end method setSocialSecurityNumber // return social security number public String getSocialSecurityNumber() { return socialSecurityNumber. testMonth ). else // month is invalid { System. } // end Date constructor // utility method to confirm proper month value private int checkMonth( int testMonth ) { if ( testMonth > 0 && testMonth <= 12 ) // validate month return testMonth. } // end method getDay . // validate month year = theYear. 31.out.printf( "Date object constructor for date %s\n". // 1-12 private int day. 30. 31. 31. 30.\n".java // Date class declaration with get methods added.out. // check for leap year if ( month == 2 && testDay == 29 && ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) ) ) return testDay. // validate day System. // maintain object in consistent state } // end method checkDay // return day public int getDay() { return day. 30.\n".printf( "Invalid month (%d) set to 1. 31. return 1. public class Date { private int month. // maintain object in consistent state } // end else } // end method checkMonth // utility method to confirm proper day value based on month and year private int checkDay( int testDay ) { int daysPerMonth[] = { 0. // call checkDay to confirm proper value for day public Date( int theMonth.printf( "Invalid day (%d) set to 1. testDay ). 28.56 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Name: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 // Programming Challenge 1: Date.out. return 1. int theYear ) { month = checkMonth( theMonth ). toString() ). 31 }. 31. // any year // constructor: call checkMonth to confirm proper value for month. 30. // 1-31 based on month private int year. // could validate year day = checkDay( theDay ). int theDay. 31. // check if day in range for month if ( testDay > 0 && testDay <= daysPerMonth[ month ] ) return testDay. System. Chapter 10 Object-Oriented Programming: Polymorphism 57 Postlab Activities Programming Challenges Name: 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 // return month public int getMonth() { return month. // seven-argument constructor public SalariedEmployee( String first. } // end method toString } // end class Date 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 // Programming Challenge 1: SalariedEmployee. override abstract method earnings in Employee public double earnings() { return getWeeklySalary(). month. public class SalariedEmployee extends Employee { private double weeklySalary. ssn. int month. String ssn. last. String last. } // end method getWeeklySalary // calculate earnings. } // end method setWeeklySalary // return salary public double getWeeklySalary() { return weeklySalary. setWeeklySalary( salary ). year ). year ). day. } // end method earnings // return String representation of SalariedEmployee object public String toString() { .0 : salary. double salary ) { super( first. } // end seven-argument SalariedEmployee constructor // set salary public void setWeeklySalary( double salary ) { weeklySalary = salary < 0. } // end method getMonth // return year public int getYear() { return year. int day. } // end method getYear // return a String of the form month/day/year public String toString() { return String.0 ? 0. int year.format( "%d/%d/%d". month.java // SalariedEmployee class derived from Employee. day. month. double hoursWorked ) { super( first.0 : hourlyWage. double hourlyWage. String last.40 ) * getWage() * 1. int day.5.toString(). } // end method getWage // set hours worked public void setHours( double hoursWorked ) { hours = ( ( hoursWorked >= 0.58 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Name: 37 38 39 40 return String. String ssn. ssn. // wage per hour private double hours. int month. int year. } // end method toString } // end class SalariedEmployee 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // Programming Challenge 1: HourlyEmployee. } // end method getHours // calculate earnings.format( "salaried employee: %s\n%s: $%. setWage( hourlyWage ).java // HourlyEmployee class derived from Employee.. "weekly salary". day.0. setHours( hoursWorked ). super. getWeeklySalary() ).2f". public class HourlyEmployee extends Employee { private double wage. year ). override abstract method earnings in Employee public double earnings() { if ( getHours() <= 40 ) // no overtime return getWage() * getHours(). last. } // end eight-argument HourlyEmployee constructor // set wage public void setWage( double hourlyWage ) { wage = hourlyWage < 0.0 ) && ( hoursWorked <= 168. } // end method setWage // return wage public double getWage() { return wage. // hours worked for week // eight-argument constructor public HourlyEmployee( String first. } // end method setHours // return hours worked public double getHours() { return hours. else return 40 * getWage() + ( getHours() .0 ) ) ? hoursWorked : 0.0 ? 0. } // end method earnings . "hours worked". override abstract method earnings in Employee public double earnings() { return getCommissionRate() * getGrossSales(). } // end method toString } // end class HourlyEmployee 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // Programming Challenge 1: CommissionEmployee. %s: %. double rate ) { super( first. last.2f". day.0 ? 0. setCommissionRate( rate ). setGrossSales( sales ). String last.Chapter 10 Object-Oriented Programming: Polymorphism 59 Postlab Activities Programming Challenges Name: 53 54 55 56 57 58 59 60 // return String representation of HourlyEmployee object public String toString() { return String. } // end method getGrossSales // calculate earnings.2f. } // end method setGrossSales // return gross sales amount public double getGrossSales() { return grossSales. } // end method getCommissionRate // set gross sales amount public void setGrossSales( double sales ) { grossSales = sales < 0.0 : sales. super. "hourly wage". } // end method earnings . // gross weekly sales private double commissionRate. getHours() )..0. month. int month.toString(). // commission percentage // eight-argument constructor public CommissionEmployee( String first.0 ) ? rate : 0. double sales..0 && rate < 1. int day.java // CommissionEmployee class derived from Employee. String ssn. public class CommissionEmployee extends Employee { private double grossSales.format( "hourly employee: %s\n%s: $%. ssn. } // end method setCommissionRate // return commission rate public double getCommissionRate() { return commissionRate. year ). getWage(). int year. } // end eight-argument CommissionEmployee constructor // set commission rate public void setCommissionRate( double rate ) { commissionRate = ( rate > 0. "commission rate". int month. } // end method earnings // return String representation of BasePlusCommissionEmployee object public String toString() { return String.. sales. } // end method toString } // end class BasePlusCommissionEmployee . override method earnings in CommissionEmployee public double earnings() { return getBaseSalary() + super. } // end method toString } // end class CommissionEmployee 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 // Programming Challenge 1: BasePlusCommissionEmployee.format( "%s: %s\n%s: $%.0 ? 0.2f". day. "gross sales".2f". int day. ssn. %s: $%. } // end method getBaseSalary // calculate earnings. String ssn. %s: %.toString().java // BasePlusCommissionEmployee class derived from CommissionEmployee. year.format( "%s %s. } // end nine-argument BasePlusCommissionEmployee constructor // set base salary public void setBaseSalary( double salary ) { baseSalary = salary < 0. "base-salaried". last. String last. super.0 : salary.. double sales. public class BasePlusCommissionEmployee extends CommissionEmployee { private double baseSalary.earnings(). "commission employee". super. getGrossSales(). // base salary per week // nine-argument constructor public BasePlusCommissionEmployee( String first. month. getBaseSalary() ).2f. "base salary". rate ).toString(). setBaseSalary( salary ). double salary ) { super( first. // non-negative } // end method setBaseSalary // return base salary public double getBaseSalary() { return baseSalary. double rate. getCommissionRate() ).60 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Name: 48 49 50 51 52 53 54 55 56 // return String representation of CommissionEmployee object public String toString() { return String. int year. salariedEmployee. // program uses Scanner to obtain user input public class PayrollSystemTest { public static void main( String args[] ) { // create subclass objects SalariedEmployee salariedEmployee = new SalariedEmployee( "John".out. System.in ). 2. 16.printf( "%s\n%s: $%. 3. "111-11-1111". System.java // Employee hierarchy test program.nextInt(). commissionEmployee.println( "Employees processed polymorphically:\n" ).Chapter 10 Object-Oriented Programming: Polymorphism 61 Postlab Activities Programming Challenges Name: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // Programming Challenge 1: PayrollSystemTest. HourlyEmployee hourlyEmployee = new HourlyEmployee( "Karen".printf( "%s\n%s: $%. . System. ..util. employees[ 1 ] = hourlyEmployee. "Lewis".out. "earned". 1965. "Jones". System. . "Price".out.println( "Employees processed individually:\n" ). hourlyEmployee. System.2f\n\n". "earned". 1944. 300 ).2f\n\n".printf( "%s\n%s: $%. import java. currentMonth = input.75. 12.earnings() ). commissionEmployee.. 1954. "333-33-3333". 5000. BasePlusCommissionEmployee basePlusCommissionEmployee = new BasePlusCommissionEmployee( "Bob". basePlusCommissionEmployee.out. "222-22-2222".Scanner. basePlusCommissionEmployee.2f\n\n". 40 ).earnings() )..out. 29. "earned".out.earnings() ). "Smith". "444-44-4444". 8.04. employees[ 2 ] = commissionEmployee. 6. // to get current month int currentMonth. // get and validate current month do { System. } while ( ( currentMonth < 1 ) || ( currentMonth > 12 ) ). salariedEmployee.12): " ). "earned". 15. // create four-element Employee array Employee employees[] = new Employee[ 4 ].00 ).06 ). System. System. CommissionEmployee commissionEmployee = new CommissionEmployee( "Sue".. hourlyEmployee.earnings() ). employees[ 3 ] = basePlusCommissionEmployee.print( "Enter the current month (1 .out. 10000. 1960.printf( "%s\n%s: $%.println().2f\n\n". Scanner input = new Scanner( System.out. 9. 800. // initialize array with Employees employees[ 0 ] = salariedEmployee. 00 birthday bonus" ).62 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Name: 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 // generically process each element in array employees for ( Employee currentEmployee : employees ) { System.getBaseSalary(). j.getName() ).2f\n\n".length. } // end main } // end class PayrollSystemTest .earnings().out.getClass(). employee. } // end if // if month of employee's birthday.2f %s\n\n". j++ ) System. currentEmployee.getBirthDate(). "plus $100.. employee.2f\n".10 * oldBaseSalary ). employees[ j ].printf( "earned $%.getBaseSalary() ).out. currentEmployee.out. add $100 to salary if ( currentMonth == currentEmployee.. double oldBaseSalary = employee.out.printf( "earned $%.printf( "Employee %d is a %s\n".. j < employees. System. } // end for // get type name of each object in employees array for ( int j = 0.out.println( currentEmployee ).setBaseSalary( 1. else System. // invokes toString // determine whether element is a BasePlusCommissionEmployee if ( currentEmployee instanceof BasePlusCommissionEmployee ) { // downcast Employee reference to // BasePlusCommissionEmployee reference BasePlusCommissionEmployee employee = ( BasePlusCommissionEmployee ) currentEmployee.printf( "new base salary with 10%% increase is: $%.earnings() ).getMonth() ) System. } // end two-argument Shape constructor // set x coordinate public void setX( int x ) { this.y = y. display its area. If a shape is a ThreeDimensionalShape.y = y. Create a program that uses an array of Shape references to objects of each concrete class in the hierarchy. Each TwoDimensionalShape should contain method getArea to calculate the area of the two-dimensional shape.3 of Java How to Program. // x coordinate private int y. int y ) { this. this.x = x. // y coordinate // two-argument constructor public Shape( int x. Each ThreeDimensionalShape should have methods getArea and getVolume to calculate the surface area and volume. If a shape is a TwoDimensionalShape.Chapter 10 Object-Oriented Programming: Polymorphism 63 Postlab Activities Programming Challenges Name: 2.x = x. 61] side: 8 Cube's area is 384 Cube's volume is 512 Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Programming Challenge 2: Shape. in the loop that processes all the shapes in the array. } // end method setX // set y coordinate public void setY( int y ) { this. Hint: • Your output should appear as follows: Circle: [22.java // Definition of class Shape. } // end method setY . of the three-dimensional shape. 88] radius: 4 Circle's area is 50 Square: [71. (Shape Hierarchy) Implement the Shape hierarchy shown in Fig. display its area and volume. public abstract class Shape { private int x. determine whether each shape is a TwoDimensionalShape or a ThreeDimensionalShape. The program should print a text description of the object to which each array element refers. 96] side: 10 Square's area is 100 Sphere: [8. Also. 89] radius: 2 Sphere's area is 50 Sphere's volume is 33 Cube: [79. 9. respectively. int d2 ) { super( x. %d)". } // end four-argument TwoDimensionalShape constructor // set methods public void setDimension1( int d ) { dimension1 = d. y ). // four-argument constructor public TwoDimensionalShape( int x. } // end method getDimension1 . } // end method getX // get y coordinate public int getY() { return y.64 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Name: 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // get x coordinate public int getX() { return x.format( "(%d. private int dimension2.java // Definition of class TwoDimensionalShape. int y. } // end method setDimension2 // get methods public int getDimension1() { return dimension1. getY() ). getX(). } // abstract methods public abstract String getName(). } // end class Shape 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Programming Challenge 2: TwoDimensionalShape. public abstract class TwoDimensionalShape extends Shape { private int dimension1. int d1. dimension2 = d2. dimension1 = d1. } // end method setDimension1 public void setDimension2( int d ) { dimension2 = d. } // end method getY // return String representation of Shape object public String toString() { return String. } // end method getDimension2 // abstract method public abstract int getArea(). getRadius() ). int radius ) { super( x.toString(). public class Circle extends TwoDimensionalShape { // three-argument constructor public Circle( int x. int y. } // end method toString } // end class Circle .format( "%s %s: %d\n". } // end method getArea // set method public void setRadius( int radius ) { setDimension1( radius ).java // Definition of class Circle. } // end method getName public int getArea() { return ( int ) ( Math.PI * getRadius() * getRadius() ). setDimension2( radius ). } // end method setRadius // get method public int getRadius() { return getDimension1().Chapter 10 Object-Oriented Programming: Polymorphism 65 Postlab Activities Programming Challenges Name: 34 35 36 37 38 39 40 41 public int getDimension2() { return dimension2. super. radius. } // end class TwoDimensionalShape 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 // Programming Challenge 2: Circle. } // end three-argument Circle constructor // overridden methods public String getName() { return "Circle". } // end method getRadius public String toString() { return String. radius ). "radius". y. setDimension2( side ). dimension1 = d1. public class Square extends TwoDimensionalShape { // three-argument constructor public Square( int x. getSide() ). side. super.java // Definition of class ThreeDimensionalShape.66 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Name: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 // Programming Challenge 2: Square. int d3 ) { super( x. } // end three-argument Square constructor // overridden methods public String getName() { return "Square". } // end method toString } // end class Square 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Programming Challenge 2: ThreeDimensionalShape.format( "%s %s: %d\n". int d1. // five-argument constructor public ThreeDimensionalShape( int x.java // Definition of class Square. int y. . } // end method getName public int getArea() { return getSide() * getSide(). int d2. private int dimension2. "side". y. } // end method getSide public String toString() { return String. } // end method setSide // get method public int getSide() { return getDimension1().toString(). } // end method getArea // set method public void setSide( int side ) { setDimension1( side ). int y. y ). private int dimension3. int side ) { super( x. side ). public abstract class ThreeDimensionalShape extends Shape { private int dimension1. radius ). } // end method setDimension2 public void setDimension3( int d ) { dimension3 = d. } // end three-argument Shape constructor // overridden methods public String getName() { return "Sphere". public abstract int getVolume(). radius. public class Sphere extends ThreeDimensionalShape { // three-argument constructor public Sphere( int x. y. } // end method getDimension1 public int getDimension2() { return dimension2. } // end method getDimension2 public int getDimension3() { return dimension3. } // end five-argument ThreeDimensionalShape constructor // set methods public void setDimension1( int d ) { dimension1 = d. } // end method setDimension1 public void setDimension2( int d ) { dimension2 = d. int y. } // end method getName . dimension3 = d3. radius. } // end class ThreeDimensionalShape 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // Programming Challenge 2: Sphere. } // end method setDimension3 // get methods public int getDimension1() { return dimension1. } // end method getDimension3 // abstract methods public abstract int getArea().java // Definition of class Sphere.Chapter 10 Object-Oriented Programming: Polymorphism 67 Postlab Activities Programming Challenges Name: 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 dimension2 = d2. int radius ) { super( x. } // end method getArea public int getVolume() { .java // Definition of class Cube.0 * Math. side ). setDimension3( radius ). side.toString(). } // end method getName public int getArea() { return ( int ) ( 6 * getSide() * getSide() ). int side ) { super( x. } // end method getRadius public String toString() { return String. super. getRadius() ).0 / 3. "radius". side.PI * getRadius() * getRadius() * getRadius() ).68 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Name: 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 public int getArea() { return ( int ) ( 4 * Math. setDimension2( radius ). y. } // end method toString } // end class Sphere 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Programming Challenge 2: Cube. } // end method setRadius // get method public int getRadius() { return getDimension1(). } // end method getVolume // set method public void setRadius( int radius ) { setDimension1( radius ). public class Cube extends ThreeDimensionalShape { // three-argument constructor public Cube( int x.PI * getRadius() * getRadius() ).format( "%s %s: %d\n". } // end three-argument Cube constructor // overridden methods public String getName() { return "Cube". } // end method getArea public int getVolume() { return ( int ) ( 4. int y. out. twoDimensionalShape. } // end if if ( currentShape instanceof ThreeDimensionalShape ) { ThreeDimensionalShape threeDimensionalShape = ( ThreeDimensionalShape ) currentShape. if ( currentShape instanceof TwoDimensionalShape ) { TwoDimensionalShape twoDimensionalShape = ( TwoDimensionalShape ) currentShape.format( "%s %s: %d\n". 88. 4 ).out. } // end method toString } // end class Cube 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Programming Challenge 2: ShapeTest. 89. System. } // end method getVolume // set method public void setSide( int side ) { setDimension1( side ). shapes[ 1 ] = new Square( 71. super. currentShape ). "side". shapes[ 0 ] = new Circle( 22.printf( "%s: %s".getName(). setDimension3( side ).Chapter 10 Object-Oriented Programming: Polymorphism 69 Postlab Activities Programming Challenges Name: 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 return ( int ) ( getSide() * getSide() * getSide() ).printf( "%s's area is %s\n".getName().java // Program tests the Shape hierarchy. . getSide() ). currentShape. shapes[ 3 ] = new Cube( 79. 61.toString(). } // end method setSide // get method public int getSide() { return getDimension1(). currentShape. setDimension2( side ). 2 ). shapes[ 2 ] = new Sphere( 8. // call method print on all shapes for ( Shape currentShape : shapes ) { System. public class ShapeTest { // create Shape objects and display their information public static void main( String args[] ) { Shape shapes[] = new Shape[ 4 ].getArea() ). 10 ). 8 ). 96. } // end method getSide public String toString() { return String. System. } // end if System.getName(). threeDimensionalShape.println(). threeDimensionalShape.out.getVolume() ).out. } // end for } // end main } // end class ShapeTest . currentShape.70 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Name: 34 35 36 37 38 39 40 41 42 43 44 45 System.getName().out.getArea() ). currentShape.printf( "%s's area is %s\n".printf( "%s's volume is %s\n".
Copyright © 2024 DOKUMEN.SITE Inc.