O my soul?

parentpitaΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

2.084 εμφανίσεις

10
Object-Oriented
Programming:
Polymorphism
OBJ ECTI VES
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 polymorphismmakes 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
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 are
intended to test and reinforce your understanding of key concepts.You may answer the questions before or dur-
ing the lab.
For each termin the left column, write the letter for the description from the right column that best matches the
term.
Term
Description
1.abstract method
2.getClass method
3.implements keyword
4. type-wrapper classes
5.downcasting
6.concrete class
7.polymorphism
8.instanceof
9.final
10.getName method
11.abstract class
12.interface
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 can-
not 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 ref-
erence 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.
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 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 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 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.
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; aimfor
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?
Prelab Activities Name:
Short Answer
10 Object-Oriented Programming:Polymorphism Chapter 10
25.Describe how to determine the class name of an object’s 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 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.)
Prelab Activities Name:
Programming Output
12 Object-Oriented Programming:Polymorphism Chapter 10
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
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.)
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
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
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.)
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 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
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 );
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 );
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 Programming
Output Exercise 28.
Your answer:
30.What is output by the following code segment?Assume that the code follows the statements in Programming
Output 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 it
is a logic error or a syntax error,circle the error in the programand 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
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 hour
plus their tips for the week.
Your answer:
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
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 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 }
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
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 problemis intended to be solved in a closed-lab session with a teaching assistant or instructor present.The
problemis divided into six parts:
1.Lab Objectives
2.Description of the Problem
3.Sample Output
4.ProgramTemplate (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 fromChapter 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 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 earn-
ings 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.
Lab Exercises Name:
Lab Exercise 1 —Payroll System Modification
22 Object-Oriented Programming:Polymorphism Chapter 10
Sample Output
ProgramTemplate
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
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
14 } // end five-argument PieceWorker constructor
15
16 // set wage
17
18
19 // return wage
20
21
22 // set pieces produced
23
24
Fig.L 10.4 | PieceWorker.java.(Part 1 of 2.)
/* declare instance variable wage */
/* declare instance variable pieces */
/* write code to initialize a PieceWorker */
/* write a set method that validates and sets the PieceWorker's wage */
/* write a get method that returns the PieceWorker's wage */
/* write a set method that validates and sets the number of pieces produced */
Lab Exercises Name:
Lab Exercise 1 —Payroll System Modification
Chapter 10 Object-Oriented Programming:Polymorphism 23
Problem-Solving Tips
1.The PieceWorker constructor should call the superclass Employee constructor to initialize the employ-
ee’s name.
25 // return pieces produced
26
27
28 // calculate earnings; override abstract method earnings in Employee
29 public double earnings()
30 {
31
32 }// end method earnings
33
34 // return String representation of PieceWorker object
35 public String toString()
36 {
37
38 }// end method toString
39 }// end class PieceWorker
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
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 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?
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 SystemModification
This problemis intended to be solved in a closed-lab session with a teaching assistant or instructor present.The
problemis divided into six parts:
1.Lab Objectives
2.Description of the Problem
3.Sample Output
4.ProgramTemplate (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 fromChapter 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 an
interface.
• Using the instanceof operator to determine whether a variable refers to an object that has an is-a rela-
tionship with a particular class.
The follow-up question and activity will also give you practice:
• Comparing interfaces and abstract classes.
Description of the Problem
(Accounts Payable System Modification) In this exercise, we modify the accounts payable application 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 sub-
classes 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.
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,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
ProgramTemplate
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
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.)
Lab Exercises Name:
Lab Exercise 2 —Accounts Payable System Modification
Chapter 10 Object-Oriented Programming:Polymorphism 27
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 {
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.)
/* write a method header to satisfy the Payable interface */
Lab Exercises Name:
Lab Exercise 2 —Accounts Payable System Modification
28 Object-Oriented Programming:Polymorphism Chapter 10
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 {
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.
/* 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.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
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.)
/* 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 Tips
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.
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 payableObjects[ 4 ] =
19
20 payableObjects[ 5 ] =
21
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
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.)
/* create an HourlyEmployee object */
/* create a CommissionEmployee object */
/* create a BasePlusCommissionEmployee object */
/* write code to determine whether currentPayable is a
BasePlusCommissionEmployee object */
/* write code to give a raise */
/* write code to ouput results of the raise */
Lab Exercises Name:
Debugging
Chapter 10 Object-Oriented Programming:Polymorphism 31
Name:
Date:
Section:
Debugging
The programin this section does not compile.Fix all the syntax errors so that the program will compile success-
fully.Once the programcompiles,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
Broken Code
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
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 }
Lab Exercises Name:
Debugging
32 Object-Oriented Programming:Polymorphism Chapter 10
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;
Lab Exercises Name:
Debugging
Chapter 10 Object-Oriented Programming:Polymorphism 33
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
Lab Exercises Name:
Debugging
34 Object-Oriented Programming:Polymorphism Chapter 10
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
Lab Exercises Name:
Debugging
Chapter 10 Object-Oriented Programming:Polymorphism 35
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
Name:
Date:
Section:
Coding Exercises
These coding exercises reinforce the lessons learned in the lab and provide additional programming experience
outside the classroomand 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 fromCoding 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.
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 instance
variable 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 or
equal to 0.The constructor should set the inherited shapeName variable to the string"Square".
5.The Square class fromCoding 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.
Postlab Activities Name:
Coding Exercises
Chapter 10 Object-Oriented Programming:Polymorphism 39
7.The Rectangle class fromCoding Exercise 6 should also implement the getArea method of its abstract su-
perclass; this implementation should compute the area of the rectangle and return the result.
8.Write an application that tests the Square and Rectangle classes fromCoding 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.
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 amount
of time to complete.Write a Java programfor 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 pro-
vided for each problem to aid you in your programming.
1.(Payroll SystemModification) Modify the payroll systemof Figs.10.4–10.9 to include private instance vari-
able birthDate in class Employee.Use class Date of Fig.8.7 to represent an employee’s birthday.Add 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...)
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 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:
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
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