+ All Categories
Home > Documents > Lab8 212 Similar

Lab8 212 Similar

Date post: 02-Oct-2015
Category:
Upload: saif-nashwan
View: 260 times
Download: 0 times
Share this document with a friend
Popular Tags:
35
10 Object-Oriented Programming: Polymorphism OBJECTIVES In this chapter you will learn: The concept of polymorphism. To use overridden methods to effect polymorphism. To distinguish between abstract and concrete classes. To declare abstract methods to create abstract classes. How polymorphism makes systems extensible and maintainable. To determine an object’s type at execution time. To declare and implement interfaces. 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
Transcript
  • 10Object-OrientedProgramming:Polymorphism

    OB J ECT IVESIn 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 andmaintainable.

    To determine an objects type at execution time.

    To declare and implement interfaces.

    One Ring to rule them all,One Ring to nd them,One Ring to bring them alland in the darkness bindthem.John Ronald Reuel Tolkien

    General propositions do not decide concrete cases.Oliver Wendell Holmes

    A philosopher of imposingstature doesnt think in avacuum. Even his most abstract ideas are, to someextent, conditioned by what is or is not knownin the time when he lives.Alfred NorthWhitehead

    Why art thou cast down,O my soul?Psalms 42:5

  • Chapter 10 Object-Oriented Programming: Polymorphism 3

    Name: Date:

    Section:

    Assignment Checklist

    Exercises Assigned: Circle assignments Date Due

    Prelab Activities

    Matching YES NO

    Fill in the Blank YES NO

    Short Answer YES NO

    Programming Output YES NO

    Correct the Code YES NO

    Lab Exercises

    Exercise 1 Payroll SystemModification YES NO

    Follow-Up Question and Activity 1

    Exercise 2 Accounts Payable SystemModification 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

    Name: Date:

    Section:

    Matching

    After reading Chapter 10 of Java How to Program: Sixth Edition, answer the given questions. The questions areintended to test and reinforce your understanding of key concepts. You may answer the questions before or dur-ing the lab.

    For each term in the left column, write the letter for the description from the right column that best matches theterm.

    Term Description

    1. abstract method

    2. getClass method

    3. implements keyword

    4. type-wrapper classes

    5. downcasting

    6. concrete class

    7. polymorphism

    8. instanceof

    9. final

    10. getName method

    11. abstract class

    12. interface

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

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

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

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

    e) Uses superclass references to manipulate sets of subclass objects ina generic manner.

    f) Casting a superclass reference to a subclass reference.

    g) Cannot be instantiated; used primarily for inheritance.

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

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

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

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

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

  • Prelab Activities Name:

    Fill in the Blank

    Chapter 10 Object-Oriented Programming: Polymorphism 7

    Name: Date:

    Section:

    Fill in the Blank

    Fill in the blanks for each of the following statements:

    13. With , 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 su-perclass 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 subclasstype.

    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 ofthe method found in the .

    19. The 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.

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

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

  • Prelab Activities Name:

    Short Answer

    Chapter 10 Object-Oriented Programming: Polymorphism 9

    Name: Date:

    Section:

    Short Answer

    In the space provided, answer each of the given questions. Your answers should be as concise as possible; aim fortwo 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 allthe methods in the interface?

  • Prelab Activities Name:

    Short Answer

    10 Object-Oriented Programming: Polymorphism Chapter 10

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

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

  • Prelab Activities Name:

    Programming Output

    Chapter 10 Object-Oriented Programming: Polymorphism 11

    Name: Date:

    Section:

    Programming Output

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

    Use the class definitions in Fig. L 10.1Fig. L 10.3 when answering Programming Output Exercises 2730.

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

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

  • Prelab Activities Name:

    Programming Output

    12 Object-Oriented Programming: Polymorphism Chapter 10

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

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

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

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

  • Prelab Activities Name:

    Programming Output

    Chapter 10 Object-Oriented Programming: Polymorphism 13

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

    1 // CommissionEmployee.java2 // CommissionEmployee class extends Employee.34 public class CommissionEmployee extends Employee5 {6 private double grossSales; // gross weekly sales7 private double commissionRate; // commission percentage89 // five-argument constructor10 public CommissionEmployee( String first, String last, String ssn,11 double sales, double rate )12 {13 super( first, last, ssn );14 setGrossSales( sales );15 setCommissionRate( rate );16 } // end five-argument CommissionEmployee constructor1718 // set commission rate19 public void setCommissionRate( double rate )20 {21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;22 } // end method setCommissionRate2324 // return commission rate25 public double getCommissionRate()26 {27 return commissionRate;28 } // end method getCommissionRate2930 // set gross sales amount31 public void setGrossSales( double sales )32 {33 grossSales = ( sales < 0.0 ) ? 0.0 : sales;34 } // end method setGrossSales3536 // return gross sales amount37 public double getGrossSales()38 {39 return grossSales;40 } // end method getGrossSales41

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

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

  • Prelab Activities Name:

    Programming Output

    14 Object-Oriented Programming: Polymorphism Chapter 10

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

    Your answer:

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

    42 // calculate earnings; override abstract method earnings in Employee43 public double earnings()44 {45 return getCommissionRate() * getGrossSales(); 46 } // end method earnings 4748 // return String representation of CommissionEmployee object49 public String toString()50 {51 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f",52 "commission employee", super.toString(),53 "gross sales", getGrossSales(),54 "commission rate", getCommissionRate() ); 55 } // end method toString56 } // end class CommissionEmployee

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

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

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

  • Prelab Activities Name:

    Programming Output

    Chapter 10 Object-Oriented Programming: Polymorphism 15

    Your answer:

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

    Your answer:

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

    Your answer:

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

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

  • Prelab Activities Name:

    Correct the Code

    Chapter 10 Object-Oriented Programming: Polymorphism 17

    Name: Date:

    Section:

    Correct the Code

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

    For questions 3133 assume the following denition of abstract class Employee.

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

  • Prelab Activities Name:

    Correct the Code

    18 Object-Oriented Programming: Polymorphism Chapter 10

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

    Your answer:

    1 // TipWorker.java2 public final class TipWorker extends Employee3 {4 private double wage; // wage per hour5 private double hours; // hours worked for week6 private double tips; // tips for the week78 public TipWorker( String first, String last,9 double wagePerHour, double hoursWorked, double tipsEarned )10 {11 super( first, last ); // call superclass constructor12 setWage ( wagePerHour );13 setHours( hoursWorked );14 setTips( tipsEarned );15 }1617 // set the wage18 public void setWage( double wagePerHour )19 {20 wage = ( wagePerHour < 0 ? 0 : wagePerHour );21 }2223 // set the hours worked24 public void setHours( double hoursWorked )25 {26 hours = ( hoursWorked >= 0 && hoursWorked < 168 ? hoursWorked : 0 ); 27 }2829 // set the tips30 public void setTips( double tipsEarned )31 {32 tips = ( tipsEarned < 0 ? 0 : tipsEarned );33 }34 } // end class TipWorker

  • Prelab Activities Name:

    Correct the Code

    Chapter 10 Object-Oriented Programming: Polymorphism 19

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

    Your answer:

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

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

    1 // Test2.java2 import java.util.Scanner;34 public class Test25 {6 public static void main( String args[] )7 {8 Employee employee[];9 Scanner input = new Scanner( System.in );1011 for ( int i = 0; i < employee.length; i++ )12 {13 System.out.print( "Input first name: " );14 String firstName = input.nextLine();1516 System.out.print( "Input last name: " );17 String lastName = input.nextLine();1819 System.out.print( "Input hours worked: " );20 double hours = input.nextDouble();2122 System.out.print( "Input tips earned: " );23 double tips = input.nextDouble();2425 employee[ i ] = new Employee( firstName, lastName, 2.63, hours, tips );2627 System.out.printf( "%s %s earned $%.2f\n", employee[ i ].getFirstName(),28 employee[ i ].getLastName(), employee[ i ].earnings() );2930 input.nextLine(); // clear any remaining characters in the input stream31 } // end for32 } // end main33 } // end class Test2

  • Prelab Activities Name:

    Correct the Code

    20 Object-Oriented Programming: Polymorphism Chapter 10

    Your answer:

  • Chapter 10 Object-Oriented Programming: Polymorphism 21

    Lab Exercises

    Name: Date:

    Section:

    Lab Exercise 1 Payroll System Modification

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

    1. Lab Objectives

    2. Description of the Problem

    3. Sample Output

    4. Program Template (Fig. L 10.4Fig. L 10.5)

    5. Problem-Solving Tips

    6. Follow-Up Question and Activity

    The program template represents a complete working Java program, with one or more key lines of code replacedwith comments. Read the problem description and examine the sample output; then study the template code.Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute theprogram. Compare your output with the sample output provided. Then answer the follow-up questions. Thesource code for the template is available at www.deitel.com and www.prenhall.com/deitel.

    Lab ObjectivesThis lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Sixth Edi-tion. In this lab, you will practice:

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

    Using the updated class hierarchy in a polymorphic application.

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

    Understanding polymorphism.

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

  • Lab Exercises Name:

    Lab Exercise 1 Payroll System Modification

    22 Object-Oriented Programming: Polymorphism Chapter 10

    Sample Output

    Program Template

    Employees processed polymorphically:

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

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

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

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

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

    1 // Lab Exercise 1: PieceWorker.java2 // PieceWorker class extends Employee.34 public class PieceWorker extends Employee5 {6789 // five-argument constructor10 public PieceWorker( String first, String last, String ssn,11 double wagePerPiece, int piecesProduced )12 {1314 } // end five-argument PieceWorker constructor1516 // set wage171819 // return wage202122 // set pieces produced2324

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

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

    /* write code to initialize a PieceWorker */

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

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

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

  • Lab Exercises Name:

    Lab Exercise 1 Payroll System Modification

    Chapter 10 Object-Oriented Programming: Polymorphism 23

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

    ees name.

    25 // return pieces produced262728 // calculate earnings; override abstract method earnings in Employee29 public double earnings()30 {3132 } // end method earnings3334 // return String representation of PieceWorker object35 public String toString()36 {3738 } // end method toString39 } // end class PieceWorker

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

    Fig. L 10.5 | PayrollSystemTest.java

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

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

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

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

  • Lab Exercises Name:

    Lab Exercise 1 Payroll System Modification

    24 Object-Oriented Programming: Polymorphism Chapter 10

    2. The number of pieces produced should be greater than or equal to 0. Place this logic in the set methodfor the pieces variable.

    3. The wage should be greater than or equal to 0. Place this logic in the set method for the wage variable.

    4. The main method must explicitly create a new PieceWorker object and assign it to an element of theemployees array.

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

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

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

  • Lab Exercises Name:

    Lab Exercise 2 Accounts Payable System Modification

    Chapter 10 Object-Oriented Programming: Polymorphism 25

    Name: Date:

    Section:

    Lab Exercise 2 Accounts Payable System Modification

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

    1. Lab Objectives

    2. Description of the Problem

    3. Sample Output

    4. Program Template (Fig. L 10.6Fig. L 10.9)

    5. Problem-Solving Tips

    6. Follow-Up Question and Activity

    The program template represents a complete working Java program, with one or more key lines of code replacedwith comments. Read the problem description and examine the sample output; then study the template code.Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute theprogram. Compare your output with the sample output provided. Then answer the follow-up question. Thesource code for the template is available at www.deitel.com and www.prenhall.com/deitel.

    Lab ObjectivesThis lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Sixth Edi-tion. In this lab you will practice:

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

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

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

    Comparing interfaces and abstract classes.

    Description of the Problem(Accounts Payable System Modication) In this exercise, we modify the accounts payable application ofFigs. 10.1110.15 to include the complete functionality of the payroll application. The application should stillprocess two Invoice objects, but now should process one object of each of the four Employee subclasses(Figs. 10.510.8). If the object currently being processed is a BasePlusCommissionEmployee, the applicationshould increase the BasePlusCommissionEmployees base salary by 10%. Finally, the application should outputthe payment amount for each object. Complete the following steps to create the new application:

    a) Modify classes HourlyEmployee and CommissionEmployee to place them in the Payable hierarchy as sub-classes of the version of Employee that implements Payable (Fig. 10.13). [Hint:Change the name of methodearnings to getPaymentAmount in each subclass so that the class satisfies its inherited contract with interfacePayable.]

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

  • Lab Exercises Name:

    Lab Exercise 2 Accounts Payable System Modification

    26 Object-Oriented Programming: Polymorphism Chapter 10

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

    Sample Output

    Program Template

    Invoices and Employees processed polymorphically:

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

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

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

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

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

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

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

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

  • Lab Exercises Name:

    Lab Exercise 2 Accounts Payable System Modification

    Chapter 10 Object-Oriented Programming: Polymorphism 27

    9 // five-argument constructor10 public HourlyEmployee( String first, String last, String ssn,11 double hourlyWage, double hoursWorked )12 {13 super( first, last, ssn );14 setWage( hourlyWage ); // validate and store hourly wage15 setHours( hoursWorked ); // validate and store hours worked16 } // end five-argument HourlyEmployee constructor1718 // set wage19 public void setWage( double hourlyWage )20 {21 wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage;22 } // end method setWage2324 // return wage25 public double getWage()26 {27 return wage;28 } // end method getWage2930 // set hours worked31 public void setHours( double hoursWorked )32 {33 hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked

  • Lab Exercises Name:

    Lab Exercise 2 Accounts Payable System Modification

    28 Object-Oriented Programming: Polymorphism Chapter 10

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

    Fig. L 10.7 | CommissionEmployee.java.

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

  • Lab Exercises Name:

    Lab Exercise 2 Accounts Payable System Modification

    Chapter 10 Object-Oriented Programming: Polymorphism 29

    1 // Lab Exercise 2: BasePlusCommissionEmployee.java2 // BasePlusCommissionEmployee class extends CommissionEmployee.34 public class BasePlusCommissionEmployee extends CommissionEmployee5 {6 private double baseSalary; // base salary per week78 // six-argument constructor9 public BasePlusCommissionEmployee( String first, String last,10 String ssn, double sales, double rate, double salary )11 {12 super( first, last, ssn, sales, rate );13 setBaseSalary( salary ); // validate and store base salary14 } // end six-argument BasePlusCommissionEmployee constructor1516 // set base salary17 public void setBaseSalary( double salary )18 {19 baseSalary = ( salary < 0.0 ) ? 0.0 : salary; // non-negative20 } // end method setBaseSalary2122 // return base salary23 public double getBaseSalary()24 {25 return baseSalary;26 } // end method getBaseSalary2728 // calculate earnings; override CommissionEmployee implementation of29 // interface Payable method3031 {3233 } // end method getPaymentAmount3435 // return String representation of BasePlusCommissionEmployee object36 public String toString()37 {38 return String.format( "%s %s; %s: $%,.2f",39 "base-salaried", super.toString(),40 "base salary", getBaseSalary() );41 } // end method toString42 } // end class BasePlusCommissionEmployee

    Fig. L 10.8 | BasePlusCommissionEmployee.java.

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

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

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

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

  • Lab Exercises Name:

    Lab Exercise 2 Accounts Payable System Modification

    30 Object-Oriented Programming: Polymorphism Chapter 10

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

    2. Class BasePlusCommissionEmployeemust use its superclasss getPaymentAmountmethod along with itsown base salary to calculate its total earnings.

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

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

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

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

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

    /* create an HourlyEmployee object */

    /* create a CommissionEmployee object */

    /* create a BasePlusCommissionEmployee object */

    /* write code to determine whether currentPayable is aBasePlusCommissionEmployee object */

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

  • Lab Exercises Name:

    Debugging

    Chapter 10 Object-Oriented Programming: Polymorphism 31

    Name: Date:

    Section:

    Debugging

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

    Sample Output

    Broken Code

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

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

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

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

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

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

  • Lab Exercises Name:

    Debugging

    32 Object-Oriented Programming: Polymorphism Chapter 10

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

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

  • Lab Exercises Name:

    Debugging

    Chapter 10 Object-Oriented Programming: Polymorphism 33

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

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

  • Lab Exercises Name:

    Debugging

    34 Object-Oriented Programming: Polymorphism Chapter 10

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

  • Lab Exercises Name:

    Debugging

    Chapter 10 Object-Oriented Programming: Polymorphism 35

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

  • Chapter 10 Object-Oriented Programming: Polymorphism 37

    Postlab Activities

    Name: Date:

    Section:

    Coding Exercises

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

    For each of the following problems, write a program or a program segment that performs the specied action.

    1. Write an empty class declaration for an abstract class called Shape.

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

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

  • Postlab Activities Name:

    Coding Exercises

    38 Object-Oriented Programming: Polymorphism Chapter 10

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

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

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

  • Postlab Activities Name:

    Coding Exercises

    Chapter 10 Object-Oriented Programming: Polymorphism 39

    7. The Rectangle class from Coding Exercise 6 should also implement the getAreamethod of its abstract su-perclass; 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 programshould polymorphically compute and display the areas of both objects. Allow a user to enter the values forthe side of the square and the length and width of the rectangle.

  • Postlab Activities Name:

    Programming Challenges

    Chapter 10 Object-Oriented Programming: Polymorphism 41

    Name: Date:

    Section:

    Programming Challenges

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

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

    Hint:

    Your output should appear as follows:

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

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

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

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

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

    Enter the current month (1 - 12): 3

    (continued next page...)

  • Postlab Activities Name:

    Programming Challenges

    42 Object-Oriented Programming: Polymorphism Chapter 10

    2. (Shape Hierarchy) Implement the Shape hierarchy shown in Fig. 9.3. Each TwoDimensionalShape shouldcontain method getArea to calculate the area of the two-dimensional shape. Each ThreeDimensionalShapeshould have methods getArea and getVolume to calculate the surface area and volume, respectively, of thethree-dimensional shape. Create a program that uses an array of Shape references to objects of each concreteclass in the hierarchy. The program should print a text description of the object to which each array elementrefers. 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. Ifa shape is a ThreeDimensionalShape, display its area and volume.

    Hint:

    Your output should appear as follows:

    Employees processed polymorphically:

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

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

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

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

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

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

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

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

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

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


Recommended