Object-Oriented Programming: Polymorphism

Similar documents
Object-Oriented Programming: Polymorphism Pearson Education, Inc. All rights reserved.

final Methods and Classes

Object-Oriented Programming: Polymorphism

Polymorphism (Deitel chapter 10) (Old versions: chapter 9)

WEEK 13 EXAMPLES: POLYMORPHISM

Object Oriented Programming with C++ (24)

Inheritance Introduction. 9.1 Introduction 361

IS 0020 Program Design and Software Tools

Introduction to Classes and Objects

Polymorphism. Chapter 4. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

BBM 102 Introduction to Programming II Spring Inheritance

Cpt S 122 Data Structures. Inheritance

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

C++ Polymorphism. Systems Programming

Introduction to Classes and Objects

Inheritance Motivation

Object- Oriented Programming: Inheritance

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Chapter 9 - Object-Oriented Programming: Polymorphism

CS111: PROGRAMMING LANGUAGE II

Java How to Program, 8/e

Computer Programming Inheritance 10 th Lecture

Inheritance (Deitel chapter 9)

Object Oriented Design

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

CS313D: ADVANCED PROGRAMMING LANGUAGE

Introduction to Java Applications

Object Oriented Programming. Java-Lecture 11 Polymorphism

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Fig Fig Fig. 10.3

Yanbu University College Applied Computer Science (ACS) Introduction to Computer Science (CS 102) Lab Exercise 10

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II

CS313D: ADVANCED PROGRAMMING LANGUAGE

Control Statements: Part 1

Inheritance and Polymorphism

CS111: PROGRAMMING LANGUAGE II

Solutions for H7. Lecture: Xu Ying Liu

BBM 102 Introduction to Programming II Spring Abstract Classes and Interfaces

BBM 102 Introduction to Programming II Spring 2017

Chapter 9 - Object-Oriented Programming: Inheritance

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 14 Abstract Classes and Interfaces

Inheritance and Polymorphism

Classes and Objects: A Deeper Look

Programming in C# Inheritance and Polymorphism

Chapter 7. Inheritance

Inheritance (continued) Inheritance

Big software. code reuse: The practice of writing program code once and using it in many contexts.

ITI Introduction to Computing II

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

Computer Science II (20073) Week 1: Review and Inheritance

9/10/2018 Programming Data Structures Inheritance

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy

Making New instances of Classes

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

CH. 2 OBJECT-ORIENTED PROGRAMMING

Java Object Oriented Design. CSC207 Fall 2014

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

ITI Introduction to Computing II

Introduction to Object-Oriented Programming

Lecture Notes Chapter #9_b Inheritance & Polymorphism

CSC330 Object Oriented Programming. Inheritance

INHERITANCE. Spring 2019

ITI Introduction to Computing II

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Object Oriented Relationships

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

5/24/12. Introduction to Polymorphism. Chapter 8. Late Binding. Introduction to Polymorphism. Late Binding. Polymorphism and Abstract Classes

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

CS 209 Sec. 52 Spring, 2006 Lab 6 - B: Inheritance Instructor: J.G. Neal

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Programming in the large

CS1150 Principles of Computer Science Objects and Classes

Chapter 19 - C++ Inheritance

Accelerating Information Technology Innovation

Chapter 20 - C++ Virtual Functions and Polymorphism

25. Generic Programming

Arrays OBJECTIVES. In this chapter you will learn:

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

What is Inheritance?

Introduction to Programming Using Java (98-388)

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Software Development With Java CSCI

Transcription:

10 One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them. John Ronald Reuel Tolkien General propositions do not decide concrete cases. Oliver Wendell Holmes A philosopher of imposing stature doesn t think in a vacuum. Even his most abstract ideas are, to some extent, conditioned by what is or is not known in the time when he lives. Alfred North Whitehead Why art thou cast down, O my soul? Psalms 42:5 Object-Oriented Programming: Polymorphism OBJECTIVES In this chapter you will learn: The concept of polymorphism. To use overridden methods to effect polymorphism. To distinguish between abstract and concrete classes. To declare abstract methods to create abstract classes. How polymorphism makes systems extensible and maintainable. To determine an object s type at execution time. To declare and implement interfaces.

Chapter 10 Object-Oriented Programming: Polymorphism 3 Assignment Checklist Date: Section: Exercises Assigned: Circle assignments Date Due Prelab Activities Matching YES NO Fill in the Blank YES NO Short Answer YES NO Programming Output YES NO Correct the Code YES NO Lab Exercises Exercise 1 Payroll System Modification YES NO Follow-Up Question and Activity 1 Exercise 2 Accounts Payable System Modification YES NO Follow-Up Question and Activity 1 Debugging YES NO Labs Provided by Instructor 1. 2. 3. Postlab Activities Coding Exercises 1, 2, 3, 4, 5, 6, 7, 8 Programming Challenges 1, 2

Chapter 10 Object-Oriented Programming: Polymorphism 5 Prelab Activities Matching Date: Section: After reading Chapter 10 of Java How to Program: Sixth Edition, answer the given questions. The questions are intended to test and reinforce your understanding of key concepts. You may answer the questions before or during the lab. For each term in the left column, write the letter for the description from the right column that best matches the term. Term 1. abstract method 2. getclass method 3. implements keyword 4. type-wrapper classes 5. downcasting 6. concrete class 7. polymorphism 8. instanceof 9. final 10. getname method 11. abstract class 12. interface Description a) Can be used in place of an abstract class when there is no default implementation to inherit. b) Indicates that a method cannot be overridden or that a class cannot be a superclass. c) Class method which returns the name of the class associated with the Class object. d) An operator that returns true if its left operand (a variable of a reference type) has the is-a relationship with its right operand (a class or interface name). e) Uses superclass references to manipulate sets of subclass objects in a generic manner. f) Casting a superclass reference to a subclass reference. g) Cannot be instantiated; used primarily for inheritance. h) Indicates that a class will declare each method in an interface with the signature specified in the interface declaration. i) Must be overridden in a subclass; otherwise, the subclass must be declared abstract. j) Returns an object that can be used to determine information about the object s class. k) A class that can be used to create objects. l) Classes in the java.lang package that are used to create objects containing values of primitive types.

Chapter 10 Object-Oriented Programming: Polymorphism 7 Prelab Activities Fill in the Blank Fill in the Blank Date: Section: Fill in the blanks for each of the following statements: 13. With, it becomes possible to design and implement systems that are more extensible. 14. Although we cannot instantiate objects of abstract superclasses, we can declare of abstract superclass types. 15. It is a syntax error if a class with one or more abstract methods is not explicitly declared. 16. It is possible to assign a superclass reference to a subclass variable by the reference to the subclass type. 17. A(n) may contain a set of public abstract methods and/or public static final fields. 18. When a method is invoked through a superclass reference to a subclass object, Java executes the version of the method found in the. 19. The operator determines whether the type of the object to which its left operand refers has an isa relationship with the type specified as its right operand. 20. To use an interface, a class must specify that it the interface and must declare every method in the interface with the signatures specified in the interface declaration. 21. When a class implements an interface, it establishes an relationship with the interface type.

Chapter 10 Object-Oriented Programming: Polymorphism 9 Prelab Activities Short Answer Short Answer Date: Section: In the space provided, answer each of the given questions. Your answers should be as concise as possible; aim for two or three sentences. 22. Describe the concept of polymorphism. 23. Define what it means to declare a method final and what it means to declare a class final. 24. What happens when a class specifies that it implements an interface, but does not provide declarations of all the methods in the interface?

10 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Short Answer 25. Describe how to determine the class name of an object s class. 26. Distinguish between an abstract class and a concrete class.

Chapter 10 Object-Oriented Programming: Polymorphism 11 Prelab Activities Programming Output Programming Output Date: Section: For each of the given program segments, read the code and write the output in the space provided below each program. [ Note: Do not execute these programs on a computer.] Use the class definitions in Fig. L 10.1 Fig. L 10.3 when answering Programming Output Exercises 27 30. 1 // Employee.java 2 // Employee abstract superclass. 3 4 public abstract class Employee 5 { 6 private String firstname; 7 private String lastname; 8 private String socialsecuritynumber; 9 10 // three-argument constructor 11 public Employee( String first, String last, String ssn ) 12 { 13 firstname = first; 14 lastname = last; 15 socialsecuritynumber = ssn; 16 } // end three-argument Employee constructor 17 18 // set first name 19 public void setfirstname( String first ) 20 { 21 firstname = first; 22 } // end method setfirstname 23 24 // return first name 25 public String getfirstname() 26 { 27 return firstname; 28 } // end method getfirstname 29 30 // set last name 31 public void setlastname( String last ) 32 { 33 lastname = last; 34 } // end method setlastname 35 36 // return last name 37 public String getlastname() 38 { 39 return lastname; 40 } // end method getlastname 41 Fig. L 10.1 Employee abstract superclass. (Part 1 of 2.)

12 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Programming Output 42 // set social security number 43 public void setsocialsecuritynumber( String ssn ) 44 { 45 socialsecuritynumber = ssn; // should validate 46 } // end method setsocialsecuritynumber 47 48 // return social security number 49 public String getsocialsecuritynumber() 50 { 51 return socialsecuritynumber; 52 } // end method getsocialsecuritynumber 53 54 // return String representation of Employee object 55 public String tostring() 56 { 57 return String.format( "%s %s\nsocial security number: %s", 58 getfirstname(), getlastname(), getsocialsecuritynumber() ); 59 } // end method tostring 60 61 // abstract method overridden by subclasses 62 public abstract double earnings(); // no implementation here 63 } // end abstract class Employee Fig. L 10.1 Employee abstract superclass. (Part 2 of 2.) 1 // SalariedEmployee.java 2 // SalariedEmployee class extends Employee. 3 4 public class SalariedEmployee extends Employee 5 { 6 private double weeklysalary; 7 8 // four-argument constructor 9 public SalariedEmployee( String first, String last, String ssn, 10 double salary ) 11 { 12 super ( first, last, ssn ); // pass to Employee constructor 13 setweeklysalary( salary ); // validate and store salary 14 } // end four-argument SalariedEmployee constructor 15 16 // set salary 17 public void setweeklysalary( double salary ) 18 { 19 weeklysalary = salary < 0.0? 0.0 : salary; 20 } // end method setweeklysalary 21 22 // return salary 23 public double getweeklysalary() 24 { 25 return weeklysalary; 26 } // end method getweeklysalary 27 28 // calculate earnings; override abstract method earnings in Employee 29 public double earnings() 30 { Fig. L 10.2 SalariedEmployee class derived from Employee. (Part 1 of 2.)

Chapter 10 Object-Oriented Programming: Polymorphism 13 Prelab Activities Programming Output 31 return getweeklysalary(); 32 } // end method earnings 33 34 // return String representation of SalariedEmployee object 35 public String tostring() 36 { 37 return String.format( "salaried employee: %s\n%s: $%,.2f", 38 super.tostring(), "weekly salary", getweeklysalary() ); 39 } // end method tostring 40 } // end class SalariedEmployee Fig. L 10.2 SalariedEmployee class derived from Employee. (Part 2 of 2.) 1 // CommissionEmployee.java 2 // CommissionEmployee class extends Employee. 3 4 public class CommissionEmployee extends Employee 5 { 6 private double grosssales; // gross weekly sales 7 private double commissionrate; // commission percentage 8 9 // five-argument constructor 10 public CommissionEmployee( String first, String last, String ssn, 11 double sales, double rate ) 12 { 13 super ( first, last, ssn ); 14 setgrosssales( sales ); 15 setcommissionrate( rate ); 16 } // end five-argument CommissionEmployee constructor 17 18 // set commission rate 19 public void setcommissionrate( double rate ) 20 { 21 commissionrate = ( rate > 0.0 && rate < 1.0 )? rate : 0.0 ; 22 } // end method setcommissionrate 23 24 // return commission rate 25 public double getcommissionrate() 26 { 27 return commissionrate; 28 } // end method getcommissionrate 29 30 // set gross sales amount 31 public void setgrosssales( double sales ) 32 { 33 grosssales = ( sales < 0.0 )? 0.0 : sales; 34 } // end method setgrosssales 35 36 // return gross sales amount 37 public double getgrosssales() 38 { 39 return grosssales; 40 } // end method getgrosssales 41 Fig. L 10.3 CommissionEmployee class derived from Employee. (Part 1 of 2.)

14 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Programming Output 42 // calculate earnings; override abstract method earnings in Employee 43 public double earnings() 44 { 45 return getcommissionrate() * getgrosssales(); 46 } // end method earnings 47 48 // return String representation of CommissionEmployee object 49 public String tostring() 50 { 51 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", 52 "commission employee", super.tostring(), 53 "gross sales", getgrosssales(), 54 "commission rate", getcommissionrate() ); 55 } // end method tostring 56 } // end class CommissionEmployee Fig. L 10.3 CommissionEmployee class derived from Employee. (Part 2 of 2.) 27. What is output by the following code segment? Assume that the code appears in the main method of an application. 1 SalariedEmployee employee1 = 2 new SalariedEmployee( "June", "Bug", "123-45-6789", 1000.00 ); 3 4 CommissionEmployee employee2 = 5 new CommissionEmployee( "Archie", "Tic", "987-65-4321", 15000.00, 0.10 ); 6 7 System.out.printf( "Employee 1:\n%s\n\n", employee1 ); 8 System.out.printf( "Employee 2:\n%s\n\n", employee2 ); Your answer: 28. What is output by the following code segment? Assume that the code appears in the main method of an application. 1 Employee firstemployee = 2 new SalariedEmployee( "June", "Bug", "123-45-6789", 1000.00 ); 3 4 Employee secondemployee = 5 new CommissionEmployee( "Archie", "Tic", "987-65-4321", 15000.00, 0.10 ); 6 7 System.out.printf( "Employee 1:\n%s\n\n", firstemployee ); 8 System.out.printf( "Employee 2:\n%s\n\n", secondemployee );

Chapter 10 Object-Oriented Programming: Polymorphism 15 Prelab Activities Programming Output Your answer: 29. What is output by the following code segment? Assume that the code follows the statements in Programming Output Exercise 28. 1 SalariedEmployee salaried = ( SalariedEmployee ) firstemployee; 2 System.out.printf( "salaried:\n%s\n", salaried ); Your answer: 30. What is output by the following code segment? Assume that the code follows the statements in Programming Output Exercise 29. 1 CommissionEmployee commission = ( CommissionEmployee ) firstemployee; 2 System.out.println( "commission:\n%s\n", commission ); Your answer:

Chapter 10 Object-Oriented Programming: Polymorphism 17 Prelab Activities Correct the Code Correct the Code Date: Section: Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a syntax error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write no error. [ Note: There may be more than one error in a program segment.] For questions 31 33 assume the following definition of abstract class Employee. 1 // Employee abstract superclass. 2 3 public abstract class Employee 4 { 5 private String firstname; 6 private String lastname; 7 8 // three-argument constructor 9 public Employee( String first, String last ) 10 { 11 firstname = first; 12 lastname = last; 13 } // end three-argument Employee constructor 14 15 // return first name 16 public String getfirstname() 17 { 18 return firstname; 19 } // end method getfirstname 20 21 // return last name 22 public String getlastname() 23 { 24 return lastname; 25 } // end method getlastname 26 27 // return String representation of Employee object 28 public String tostring() 29 { 30 return String.format( "%s %s", getfirstname(), getlastname() ); 31 } // end method tostring 32 33 // abstract method overridden by subclasses 34 public abstract double earnings(); // no implementation here 35 } // end abstract class Employee

18 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Correct the Code 31. The following concrete class should inherit from abstract class Employee. A TipWorker is paid by the hour plus their tips for the week. 1 // TipWorker.java 2 public final class TipWorker extends Employee 3 { 4 private double wage; // wage per hour 5 private double hours; // hours worked for week 6 private double tips; // tips for the week 7 8 public TipWorker( String first, String last, 9 double wageperhour, double hoursworked, double tipsearned ) 10 { 11 super ( first, last ); // call superclass constructor 12 setwage ( wageperhour ); 13 sethours( hoursworked ); 14 settips( tipsearned ); 15 } 16 17 // set the wage 18 public void setwage( double wageperhour ) 19 { 20 wage = ( wageperhour < 0? 0 : wageperhour ); 21 } 22 23 // set the hours worked 24 public void sethours( double hoursworked ) 25 { 26 hours = ( hoursworked >= 0 && hoursworked < 168? hoursworked : 0 ); 27 } 28 29 // set the tips 30 public void settips( double tipsearned ) 31 { 32 tips = ( tipsearned < 0? 0 : tipsearned ); 33 } 34 } // end class TipWorker Your answer:

Chapter 10 Object-Oriented Programming: Polymorphism 19 Prelab Activities Correct the Code 32. The following code should define method tostring of class TipWorker in Correct the Code Exercise 31. 1 // return a string representation of a TipWorker 2 public String tostring() 3 { 4 return String.format( 5 "Tip worker: %s\n%s: $%,.2f; %s: %.2f; %s: $%,.2f\n", tostring(), 6 "hourly wage", wage, "hours worked", hours, "tips earned", tips ); 7 } Your answer: 33. The following code should input information about five TipWorker s from the user and then print that information and all the TipWorker s calculated earnings. 1 // Test2.java 2 import java.util.scanner; 3 4 public class Test2 5 { 6 public static void main( String args[] ) 7 { 8 Employee employee[]; 9 Scanner input = new Scanner( System.in ); 10 11 for ( int i = 0 ; i < employee.length; i++ ) 12 { 13 System.out.print( "Input first name: " ); 14 String firstname = input.nextline(); 15 16 System.out.print( "Input last name: " ); 17 String lastname = input.nextline(); 18 19 System.out.print( "Input hours worked: " ); 20 double hours = input.nextdouble(); 21 22 System.out.print( "Input tips earned: " ); 23 double tips = input.nextdouble(); 24 25 employee[ i ] = new Employee( firstname, lastname, 2.63, hours, tips ); 26 27 System.out.printf( "%s %s earned $%.2f\n", employee[ i ].getfirstname(), 28 employee[ i ].getlastname(), employee[ i ].earnings() ); 29 30 input.nextline(); // clear any remaining characters in the input stream 31 } // end for 32 } // end main 33 } // end class Test2

20 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Correct the Code Your answer:

Chapter 10 Object-Oriented Programming: Polymorphism 21 Lab Exercises Lab Exercise 1 Payroll System Modification Date: Section: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 10.4 Fig. L 10.5) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at www.deitel.com and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Sixth Edition. In this lab, you will practice: Creating a new class and adding it to an existing class hierarchy. Using the updated class hierarchy in a polymorphic application. The follow-up question and activity also will give you practice: Understanding polymorphism. Description of the Problem (Payroll System Modification) Modify the payroll system of Figs. 10.4 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. 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). 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. Create an array of Employee variables to store references to objects of each concrete class in the new Employee hierarchy. For each Employee, display its string representation and earnings.

22 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 1 Payroll System Modification Sample Output Employees processed polymorphically: salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 earned $800.00 hourly employee: Karen Price social security number: 222-22-2222 hourly wage: $16.75; hours worked: 40.00 earned $670.00 commission employee: Sue Jones social security number: 333-33-3333 gross sales: $10,000.00; commission rate: 0.06 earned $600.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 earned $500.00 piece worker: Rick Bridges social security number: 555-55-5555 wage per piece: $2.25; pieces produced: 400 earned $900.00 Program Template 1 // Lab Exercise 1: PieceWorker.java 2 // PieceWorker class extends Employee. 3 4 public class PieceWorker extends Employee 5 { 6 7 8 9 // five-argument constructor 10 public PieceWorker( String first, String last, String ssn, 11 double wageperpiece, int piecesproduced ) 12 { 13 /* write code to initialize a PieceWorker */ 14 } // end five-argument PieceWorker constructor 15 16 // set wage 17 18 19 // return wage 20 21 22 // set pieces produced 23 24 /* declare instance variable wage */ /* declare instance variable pieces */ /* write a set method that validates and sets the PieceWorker's wage */ /* write a get method that returns the PieceWorker's wage */ /* write a set method that validates and sets the number of pieces produced */ Fig. L 10.4 PieceWorker.java. (Part 1 of 2.)

Chapter 10 Object-Oriented Programming: Polymorphism 23 Lab Exercises Lab Exercise 1 Payroll System Modification 25 // return pieces produced 26 /* write a get method that returns the number of pieces produced */ 27 28 // calculate earnings; override abstract method earnings in Employee 29 public double earnings() 30 { 31 /* write code to return the earnings for a PieceWorker */ 32 } // end method earnings 33 34 // return String representation of PieceWorker object 35 public String tostring() 36 { 37 /* write code to return a string representation of a PieceWorker */ 38 } // end method tostring 39 } // end class PieceWorker Fig. L 10.4 PieceWorker.java. (Part 2 of 2.) 1 // Lab Exercise 1: PayrollSystemTest.java 2 // Employee hierarchy test program. 3 4 public class PayrollSystemTest 5 { 6 public static void main( String args[] ) 7 { 8 // create five-element Employee array 9 Employee employees[] = new Employee[ 5 ]; 10 11 // initialize array with Employees 12 employees[ 0 ] = new SalariedEmployee( 13 "John", "Smith", "111-11-1111", 800.00 ); 14 employees[ 1 ] = new HourlyEmployee( 15 "Karen", "Price", "222-22-2222", 16.75, 40 ); 16 employees[ 2 ] = new CommissionEmployee( 17 "Sue", "Jones", "333-33-3333", 10000,.06 ); 18 employees[ 3 ] = new BasePlusCommissionEmployee( 19 "Bob", "Lewis", "444-44-4444", 5000,.04, 300 ); 20 /* create a PieceWoker object and assign it to employees[ 4 ] */ 21 22 System.out.println( "Employees processed polymorphically:\n" ); 23 24 // generically process each element in array employees 25 for ( Employee currentemployee : employees ) 26 { 27 System.out.println( currentemployee ); // invokes tostring 28 System.out.printf( 29 "earned $%,.2f\n\n", currentemployee.earnings() ); 30 } // end for 31 } // end main 32 } // end class PayrollSystemTest Fig. L 10.5 PayrollSystemTest.java Problem-Solving Tips 1. The PieceWorker constructor should call the superclass Employee constructor to initialize the employee s name.

24 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 1 Payroll System Modification 2. The number of pieces produced should be greater than or equal to 0. Place this logic in the set method for the pieces variable. 3. The wage should be greater than or equal to 0. Place this logic in the set method for the wage variable. 4. The main method must explicitly create a new PieceWorker object and assign it to an element of the employees array. 5. If you have any questions as you proceed, ask your lab instructor for assistance. Follow-Up Question and Activity 1. Explain the line of code in your PayrollSystemTest s main method that calls method earnings. Why can that line invoke method earnings on every element of the employees array?

Chapter 10 Object-Oriented Programming: Polymorphism 25 Lab Exercises Lab Exercise 2 Accounts Payable System Modification Lab Exercise 2 Accounts Payable System Modification Date: Section: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 10.6 Fig. L 10.9) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up question. The source code for the template is available at www.deitel.com and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Sixth Edition. In this lab you will practice: Provide additional polymorphic processing capabilities to an inheritance hierarchy by implementing an interface. Using the instanceof operator to determine whether a variable refers to an object that has an is-a relationship with a particular class. The follow-up question and activity will also give you practice: Comparing interface s and abstract classes. Description of the Problem (Accounts Payable System Modification) In this exercise, we modify the accounts payable application of Figs. 10.11 10.15 to include the complete functionality of the payroll application. The application should still process two Invoice objects, but now should process one object of each of the four Employee subclasses (Figs. 10.5 10.8). If the object currently being processed is a BasePlusCommissionEmployee, the application should increase the BasePlusCommissionEmployee s base salary by 10%. Finally, the application should output the payment amount for each object. Complete the following steps to create the new application: a) Modify classes HourlyEmployee and CommissionEmployee to place them in the Payable hierarchy as subclasses of the version of Employee that implements Payable (Fig. 10.13). [ Hint: Change the name of method earnings to getpaymentamount in each subclass so that the class satisfies its inherited contract with interface Payable.] b) Modify class BasePlusCommissionEmployee such that it extends the version of class CommissionEmployee created in Part a.

26 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 2 Accounts Payable System Modification c) Modify PayableInterfaceTest to polymorphically process two Invoice s, one SalariedEmployee, one HourlyEmployee, one CommissionEmployee and one BasePlusCommissionEmployee. First output a string representation of each Payable object. Next, if an object is a BasePlusCommissionEmployee, increase its base salary by 10%. Finally, output the payment amount for each Payable object. Sample Output Invoices and Employees processed polymorphically: invoice: part number: 01234 (seat) quantity: 2 price per item: $375.00 payment due: $750.00 invoice: part number: 56789 (tire) quantity: 4 price per item: $79.95 payment due: $319.80 salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 payment due: $800.00 hourly employee: Karen Price social security number: 222-22-2222 hourly wage: $16.75; hours worked: 40.00 payment due: $670.00 commission employee: Sue Jones social security number: 333-33-3333 gross sales: $10,000.00; commission rate: 0.06 payment due: $600.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 new base salary with 10% increase is: $330.00 payment due: $530.00 Program Template 1 // Lab Exercise 2: HourlyEmployee.java 2 // HourlyEmployee class extends Employee, which implements Payable. 3 4 public class HourlyEmployee extends Employee 5 { 6 private double wage; // wage per hour 7 private double hours; // hours worked for week 8 Fig. L 10.6 HourlyEmployee.java. (Part 1 of 2.)

Chapter 10 Object-Oriented Programming: Polymorphism 27 Lab Exercises Lab Exercise 2 Accounts Payable System Modification 9 // five-argument constructor 10 public HourlyEmployee( String first, String last, String ssn, 11 double hourlywage, double hoursworked ) 12 { 13 super ( first, last, ssn ); 14 setwage( hourlywage ); // validate and store hourly wage 15 sethours( hoursworked ); // validate and store hours worked 16 } // end five-argument HourlyEmployee constructor 17 18 // set wage 19 public void setwage( double hourlywage ) 20 { 21 wage = ( hourlywage < 0.0 )? 0.0 : hourlywage; 22 } // end method setwage 23 24 // return wage 25 public double getwage() 26 { 27 return wage; 28 } // end method getwage 29 30 // set hours worked 31 public void sethours( double hoursworked ) 32 { 33 hours = ( ( hoursworked >= 0.0 ) && ( hoursworked <= 168.0 ) )? 34 hoursworked : 0.0; 35 } // end method sethours 36 37 // return hours worked 38 public double gethours() 39 { 40 return hours; 41 } // end method gethours 42 43 // calculate earnings; implement interface Payable method not 44 // implemented by superclass Employee 45 46 /* write a method header to satisfy the Payable interface */ { 47 if ( gethours() <= 40 ) // no overtime 48 return getwage() * gethours(); 49 else 50 return 40 * getwage() + ( gethours() - 40 ) * getwage() * 1.5; 51 } // end method getpaymentamount 52 53 // return String representation of HourlyEmployee object 54 public String tostring() 55 { 56 return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f", 57 super.tostring(), "hourly wage", getwage(), 58 "hours worked", gethours() ); 59 } // end method tostring 60 } // end class HourlyEmployee Fig. L 10.6 HourlyEmployee.java. (Part 2 of 2.)

28 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 2 Accounts Payable System Modification 1 // Lab Exercise 2: CommissionEmployee.java 2 // CommissionEmployee class extends Employee, which implements Payable. 3 4 public class CommissionEmployee extends Employee 5 { 6 private double grosssales; // gross weekly sales 7 private double commissionrate; // commission percentage 8 9 // five-argument constructor 10 public CommissionEmployee( String first, String last, String ssn, 11 double sales, double rate ) 12 { 13 super ( first, last, ssn ); 14 setgrosssales( sales ); 15 setcommissionrate( rate ); 16 } // end five-argument CommissionEmployee constructor 17 18 // set commission rate 19 public void setcommissionrate( double rate ) 20 { 21 commissionrate = ( rate > 0.0 && rate < 1.0 )? rate : 0.0 ; 22 } // end method setcommissionrate 23 24 // return commission rate 25 public double getcommissionrate() 26 { 27 return commissionrate; 28 } // end method getcommissionrate 29 30 // set gross sales amount 31 public void setgrosssales( double sales ) 32 { 33 grosssales = ( sales < 0.0 )? 0.0 : sales; 34 } // end method setgrosssales 35 36 // return gross sales amount 37 public double getgrosssales() 38 { 39 return grosssales; 40 } // end method getgrosssales 41 42 // calculate earnings; implement interface Payable method not 43 // implemented by superclass Employee 44 45 /* write a method header to satisfy the Payable interface */ { 46 return getcommissionrate() * getgrosssales(); 47 } // end method getpaymentamount 48 49 // return String representation of CommissionEmployee object 50 public String tostring() 51 { 52 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", 53 "commission employee", super.tostring(), 54 "gross sales", getgrosssales(), 55 "commission rate", getcommissionrate() ); 56 } // end method tostring 57 } // end class CommissionEmployee Fig. L 10.7 CommissionEmployee.java.

Chapter 10 Object-Oriented Programming: Polymorphism 29 Lab Exercises Lab Exercise 2 Accounts Payable System Modification 1 // Lab Exercise 2: BasePlusCommissionEmployee.java 2 // BasePlusCommissionEmployee class extends CommissionEmployee. 3 4 public class BasePlusCommissionEmployee extends CommissionEmployee 5 { 6 private double basesalary; // base salary per week 7 8 // six-argument constructor 9 public BasePlusCommissionEmployee( String first, String last, 10 String ssn, double sales, double rate, double salary ) 11 { 12 super ( first, last, ssn, sales, rate ); 13 setbasesalary( salary ); // validate and store base salary 14 } // end six-argument BasePlusCommissionEmployee constructor 15 16 // set base salary 17 public void setbasesalary( double salary ) 18 { 19 basesalary = ( salary < 0.0 )? 0.0 : salary; // non-negative 20 } // end method setbasesalary 21 22 // return base salary 23 public double getbasesalary() 24 { 25 return basesalary; 26 } // end method getbasesalary 27 28 // calculate earnings; override CommissionEmployee implementation of 29 // interface Payable method 30 31 { 32 /* write a method header to satisfy the Payable interface */ /* calculate and return the BasePlusCommissionEmployee's earnings */ 33 } // end method getpaymentamount 34 35 // return String representation of BasePlusCommissionEmployee object 36 public String tostring() 37 { 38 return String.format( "%s %s; %s: $%,.2f", 39 "base-salaried", super.tostring(), 40 "base salary", getbasesalary() ); 41 } // end method tostring 42 } // end class BasePlusCommissionEmployee Fig. L 10.8 BasePlusCommissionEmployee.java. 1 // Lab Exercise 2: PayableInterfaceTest.java 2 // Tests interface Payable. 3 4 public class PayableInterfaceTest 5 { 6 public static void main( String args[] ) 7 { 8 // create six-element Payable array 9 Payable payableobjects[] = new Payable[ 6 ]; 10 Fig. L 10.9 PayableInterfaceTest.java. (Part 1 of 2.)

30 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 2 Accounts Payable System Modification 11 // populate array with objects that implement Payable 12 payableobjects[ 0 ] = new Invoice( "01234", "seat", 2, 375.00 ); 13 payableobjects[ 1 ] = new Invoice( "56789", "tire", 4, 79.95 ); 14 payableobjects[ 2 ] = 15 new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 ); 16 payableobjects[ 3 ] = 17 18 /* create an HourlyEmployee object */ payableobjects[ 4 ] = 19 /* create a CommissionEmployee object */ 20 payableobjects[ 5 ] = 21 /* create a BasePlusCommissionEmployee object */ 22 23 System.out.println( 24 "Invoices and Employees processed polymorphically:\n" ); 25 26 // generically process each element in array payableobjects 27 for ( Payable currentpayable : payableobjects ) 28 { 29 // output currentpayable and its appropriate payment amount 30 System.out.printf( "%s \n", currentpayable.tostring() ); 31 32 33 34 { 35 36 Problem-Solving Tips /* write code to determine whether currentpayable is a BasePlusCommissionEmployee object */ /* write code to give a raise */ /* write code to ouput results of the raise */ 37 } // end if 38 39 System.out.printf( "%s: $%,.2f\n\n", 40 "payment due", currentpayable.getpaymentamount() ); 41 } // end for 42 } // end main 43 } // end class PayableInterfaceTest Fig. L 10.9 PayableInterfaceTest.java. (Part 2 of 2.) 1. Every class that implements interface Payable must declare a method called getpaymentamount. 2. Class BasePlusCommissionEmployee must use its superclass s getpaymentamount method along with its own base salary to calculate its total earnings. 3. Use the instanceof operator in PayableInterfaceTest to determine whether each object is a Base- PlusCommissionEmployee object. 4. If you have any questions as you proceed, ask your lab instructor for assistance. Follow-Up Question and Activity 1. Discuss the benefits and disadvantages of extending an abstract class vs. implementing an interface.

Chapter 10 Object-Oriented Programming: Polymorphism 31 Lab Exercises Debugging Debugging Date: Section: The program in this section does not compile. Fix all the syntax errors so that the program will compile successfully. Once the program compiles, execute the program, and compare the output with the sample output; then eliminate any logic errors that may exist. The sample output demonstrates what the program s output should be once the program s code is corrected. The source code is available at www.deitel.com and at www.prenhall.com/ deitel. Sample Output Point: [7, 11] Circle: Center = [22, 8]; Radius = 3.500000 Cylinder: Center = [10, 10]; Radius = 3.300000; Height = 10.000000 Point: [7, 11] Area = 0.00 Volume = 0.00 Circle: Center = [22, 8]; Radius = 3.500000 Area = 38.48 Volume = 0.00 Cylinder: Center = [10, 10]; Radius = 3.300000; Height = 10.000000 Area = 275.77 Volume = 342.12 Broken Code 1 // Shape.java 2 // Definition of interface Shape 3 4 public interface Shape 5 { 6 public abstract String getname(); // return shape name 7 } // end interface Shape 1 // Point.java 2 // Definition of class Point 3 4 public class Point implements Shape 5 { 6 protected int x, y; // coordinates of the Point 7 8 // no-argument constructor 9 public Point() 10 { 11 setpoint( 0, 0 ); 12 }

32 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Debugging 13 14 // constructor 15 public Point( int xcoordinate, int ycoordinate ) 16 { 17 setpoint( xcoordinate, ycoordinate ); 18 } 19 20 // Set x and y coordinates of Point 21 public void setpoint( int xcoordinate, int ycoordinate ) 22 { 23 x = xcoordinate; 24 y = ycoordinate; 25 } 26 27 // get x coordinate 28 public int getx() 29 { 30 return x; 31 } 32 33 // get y coordinate 34 public int gety() 35 { 36 return y; 37 } 38 39 // convert point into String representation 40 public String tostring() 41 { 42 return String.format( "[%d, %d]", x, y ); 43 } 44 45 // calculate area 46 public double area() 47 { 48 return 0.0 ; 49 } 50 51 // calculate volume 52 public double volume() 53 { 54 return 0.0 ; 55 } 56 57 // return shape name 58 public String getname() 59 { 60 return "Point"; 61 } 62 } // end class Point 1 // Circle.java 2 // Definition of class Circle 3 4 public class Circle extends Point 5 { 6 protected double radius;

Chapter 10 Object-Oriented Programming: Polymorphism 33 Lab Exercises Debugging 7 8 // no-argument constructor 9 public Circle() 10 { 11 // implicit call to superclass constructor here 12 setradius( 0 ); 13 } 14 15 // constructor 16 public Circle( double circleradius, int xcoordinate, int ycoordinate ) 17 { 18 super ( xcoordinate, ycoordinate ); // call superclass constructor 19 20 setradius( circleradius ); 21 } 22 23 // set radius of Circle 24 public void setradius( double circleradius ) 25 { 26 radius = ( circleradius >= 0? circleradius : 0 ); 27 } 28 29 // get radius of Circle 30 public double getradius() 31 { 32 return radius; 33 } 34 35 // calculate area of Circle 36 public double area() 37 { 38 return Math.PI * radius * radius; 39 } 40 41 // convert Circle to a String represention 42 public String tostring() 43 { 44 return String.format( "Center = %s; Radius = %f", 45 super.tostring(), radius ); 46 } 47 48 // return shape name 49 public String getname() 50 { 51 return "Circle"; 52 } 53 } // end class Circle 1 // Cylinder.java 2 // Definition of class Cylinder. 3 4 public class Cylinder extends Circle 5 { 6 protected double height; // height of Cylinder 7

34 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Debugging 8 // no-argument constructor 9 public Cylinder() 10 { 11 // implicit call to superclass constructor here 12 setheight( 0 ); 13 } 14 15 // constructor 16 public Cylinder( double cylinderheight, double cylinderradius, 17 int xcoordinate, int ycoordinate ) 18 { 19 // call superclass constructor 20 super ( cylinderradius, xcoordinate, ycoordinate ); 21 22 setheight( cylinderheight ); 23 } 24 25 // set height of Cylinder 26 public void setheight( double cylinderheight ) 27 { 28 height = ( cylinderheight >= 0? cylinderheight : 0 ); 29 } 30 31 // get height of Cylinder 32 public double getheight() 33 { 34 return height; 35 } 36 37 // calculate area of Cylinder (i.e., surface area) 38 public double area() 39 { 40 return 2 * super.area() + 2 * Math.PI * radius * height; 41 } 42 43 // calculate volume of Cylinder 44 public double volume() 45 { 46 return super.area() * height; 47 } 48 49 // convert Cylinder to a String representation 50 public String tostring() 51 { 52 return String.format( "%s; Height = %f", 53 super.tostring(), height ); 54 } 55 56 // return shape name 57 public String getname() 58 { 59 return "Cylinder"; 60 } 61 } // end class Cylinder

Chapter 10 Object-Oriented Programming: Polymorphism 35 Lab Exercises Debugging 1 // Test.java 2 // Test Point, Circle, Cylinder hierarchy with interface Shape. 3 4 public class Test 5 { 6 // test Shape hierarchy 7 public static void main( String args[] ) 8 { 9 // create shapes 10 Point point = new Point( 7, 11 ); 11 Circle circle = new Circle( 3.5, 22, 8 ); 12 Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 ); 13 14 Cylinder arrayofshapes[] = new Cylinder[ 3 ]; // create Shape array 15 16 // aim arrayofshapes[ 0 ] at subclass Point object 17 arrayofshapes[ 0 ] = ( Cylinder ) point; 18 19 // aim arrayofshapes[ 1 ] at subclass Circle object 20 arrayofshapes[ 1 ] = ( Cylinder ) circle; 21 22 // aim arrayofshapes[ 2 ] at subclass Cylinder object 23 arrayofshapes[ 2 ] = ( Cylinder ) cylinder; 24 25 // get name and String representation of each shape 26 System.out.printf( "%s: %s\n%s: %s\n%s: %s\n", point.getname(), 27 point, circle.getname(), circle, cylinder.getname(), cylinder ); 28 29 // get name, area and volume of each shape in arrayofshapes 30 for ( Shape shape : arrayofshapes ) 31 { 32 System.out.printf( "\n\n%s: %s\narea = %.2f\nVolume = %.2f\n", 33 shape.getname(), shape, shape.area(), shape.volume() ); 34 } // end for 35 } // end main 36 } // end class Test

Chapter 10 Object-Oriented Programming: Polymorphism 37 Postlab Activities Coding Exercises Date: Section: These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. They serve as a review after you have successfully completed the Prelab Activities and Lab Exercises. For each of the following problems, write a program or a program segment that performs the specified action. 1. Write an empty class declaration for an abstract class called Shape. 2. In the class from Coding Exercise 1, create a protected instance variable shapename of type String, and write an accessor method getname for obtaining its value. 3. In the class of Coding Exercise 2, define an abstract method getarea that returns a double representation of a specific shape s area. Subclasses of this class must implement getarea to calculate a specific shape s area.

38 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Coding Exercises 4. Define a class Square that inherits from class Shape from Coding Exercise 3; it should contain an instance variable side, which represents the length of a side of the square. Provide a constructor that takes one argument representing the side of the square and sets the side variable. Ensure that the side is greater than or equal to 0. The constructor should set the inherited shapename variable to the string "Square". 5. The Square class from Coding Exercise 4 should implement the getarea method of its abstract superclass; this implementation should compute the area of the square and return the result. 6. Define a class Rectangle that inherits from class Shape of Coding Exercise 3. The new class should contain instance variables length and width. Provide a constructor that takes two arguments representing the length and width of the rectangle, sets the two variables and sets the inherited shapename variable to the string "Rectangle". Ensure that the length and width are both greater than or equal to 0.

Chapter 10 Object-Oriented Programming: Polymorphism 39 Postlab Activities Coding Exercises 7. The Rectangle class from Coding Exercise 6 should also implement the getarea method of its abstract superclass; this implementation should compute the area of the rectangle and return the result. 8. Write an application that tests the Square and Rectangle classes from Coding Exercises 5 and 7, respectively. Create an array of type Shape that holds an instance of Square and an instance of Rectangle. The program should polymorphically compute and display the areas of both objects. Allow a user to enter the values for the side of the square and the length and width of the rectangle.

Chapter 10 Object-Oriented Programming: Polymorphism 41 Postlab Activities Programming Challenges Programming Challenges Date: Section: The Programming Challenges are more involved than the Coding Exercises and may require a significant amount of time to complete. Write a Java program for each of the problems in this section. The answers to these problems are available at www.deitel.com and www.prenhall.com/deitel. Pseudocode, hints or sample outputs are provided for each problem to aid you in your programming. 1. (Payroll System Modification) Modify the payroll system of Figs. 10.4 10.9 to include private instance variable birthdate in class Employee. Use class Date of Fig. 8.7 to represent an employee s birthday. Add get methods to class Date and replace method todatestring with method tostring. Assume that payroll is processed once per month. Create an array of Employee variables to store references to the various employee objects. In a loop, calculate the payroll for each Employee (polymorphically), and add a $100.00 bonus to the person s payroll amount if the current month is the month in which the Employee s birthday occurs. Hint: Your output should appear as follows: Date object constructor for date 6/15/1944 Date object constructor for date 12/29/1960 Date object constructor for date 9/8/1954 Date object constructor for date 3/2/1965 Employees processed individually: salaried employee: John Smith social security number: 111-11-1111 birth date: 6/15/1944 weekly salary: $800.00 earned: $800.00 hourly employee: Karen Price social security number: 222-22-2222 birth date: 12/29/1960 hourly wage: $16.75; hours worked: 40.00 earned: $670.00 commission employee: Sue Jones social security number: 333-33-3333 birth date: 9/8/1954 gross sales: $10,000.00; commission rate: 0.06 earned: $600.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 birth date: 3/2/1965 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 earned: $500.00 Enter the current month (1-12): 3 (continued next page...)

42 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Employees processed polymorphically: salaried employee: John Smith social security number: 111-11-1111 birth date: 6/15/1944 weekly salary: $800.00 earned $800.00 hourly employee: Karen Price social security number: 222-22-2222 birth date: 12/29/1960 hourly wage: $16.75; hours worked: 40.00 earned $670.00 commission employee: Sue Jones social security number: 333-33-3333 birth date: 9/8/1954 gross sales: $10,000.00; commission rate: 0.06 earned $600.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 birth date: 3/2/1965 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 new base salary with 10% increase is: $330.00 earned $530.00 plus $100.00 birthday bonus Employee 0 is a SalariedEmployee Employee 1 is a HourlyEmployee Employee 2 is a CommissionEmployee Employee 3 is a BasePlusCommissionEmployee 2. (Shape Hierarchy) Implement the Shape hierarchy shown in Fig. 9.3. Each TwoDimensionalShape should contain method getarea to calculate the area of the two-dimensional shape. Each ThreeDimensionalShape should have methods getarea and getvolume to calculate the surface area and volume, respectively, of the three-dimensional shape. Create a program that uses an array of Shape references to objects of each concrete class in the hierarchy. The program should print a text description of the object to which each array element refers. Also, in the loop that processes all the shapes in the array, determine whether each shape is a Two- DimensionalShape or a ThreeDimensionalShape. If a shape is a TwoDimensionalShape, display its area. If a shape is a ThreeDimensionalShape, display its area and volume. Hint: Your output should appear as follows: Circle: [22, 88] radius: 4 Circle's area is 50 Square: [71, 96] side: 10 Square's area is 100 Sphere: [8, 89] radius: 2 Sphere's area is 50 Sphere's volume is 33 Cube: [79, 61] side: 8 Cube's area is 384 Cube's volume is 512