Free Essay

Java Page

In:

Submitted By squallxcx
Words 4624
Pages 19
10
One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them.
—John Ronald Reuel Tolkien

Object-Oriented Programming: Polymorphism
OBJECTIVES In this chapter you will learn:
■ ■ ■ ■ ■

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

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.

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

■ ■

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

307

Assignment Checklist
Name: Section: Date:

Exercises

Assigned: Circle assignments

Date Due

Prelab Activities
Matching Fill in the Blank Short Answer Programming Output Correct the Code YES YES YES YES YES YES 1 NO NO 1 YES NO NO NO NO NO NO

Lab Exercises
Exercise 1 — Payroll System Modification Follow-Up Question and Activity Follow-Up Question and Activity Debugging

Exercise 2 — Accounts Payable System Modification YES

Labs Provided by Instructor
1. 2. 3.

Postlab Activities
Coding Exercises Programming Challenges 1, 2, 3, 4, 5, 6, 7, 8 1, 2

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

309

Prelab Activities
Matching
Name: Section: After reading Chapter 10 of Java How to Program: Seventh Edition, answer the given questions. The questions are intended to test and reinforce your understanding of key concepts. You may answer the questions before or during the lab. For each term in the left column, write the letter for the description from the right column that best matches the term.
Term Description

Date:

1. 2. 3.

abstract getClass

method method keyword

a) Can be used in place of an abstract class when there is no default implementation to inherit. b) Indicates that a method cannot be overridden or that a class cannot be a superclass. c)
Class method which returns the name of the class associated with the Class object.

implements

4. type-wrapper classes 5. downcasting 6. concrete class 7. polymorphism 8. 9. 10. 11. instanceof final getName

d) An operator that returns true if its left operand (a variable of a reference type) has the is-a relationship with its right operand (a class or interface name). 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) j) Must be overridden in a subclass; otherwise, the subclass must be declared abstract. Returns an object that can be used to determine information about the object’s class. Classes in the java.lang package that are used to create objects containing values of primitive types.

method class

abstract

12. interface

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

311

Prelab Activities Fill in the Blank
Fill in the Blank

Name:

Name: Section:

Date:

Fill in the blanks for each of the following statements: 13. With , it becomes possible to design and implement systems that are more extensible. of abstract su-

14. Although we cannot instantiate objects of abstract superclasses, we can declare 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 type. 17. A(n)

.

the reference to the subclass

may contain a set of public abstract methods and/or public static final fields.

18. When a method is invoked through a superclass reference to a subclass object, Java executes the version of the method found in the . 19. The operator determines whether the type of the object to which its left operand refers has an isa relationship with the type specified as its right operand. 20. To use an interface, a class must specify that it the interface and must declare every method in the interface with the signatures specified in the interface declaration. 21. When a class implements an interface, it establishes an relationship with the interface type.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

313

Prelab Activities Short Answer
Short Answer

Name:

Name: Section:

Date:

In the space provided, answer each of the given questions. Your answers should be concise; aim for two or three sentences. 22. Describe the concept of polymorphism.

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

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

314

Object-Oriented Programming: Polymorphism

Chapter10

Prelab Activities Short Answer
25. Describe how to determine the class name of an object’s class.

Name:

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

315

Prelab Activities Programming Output
Programming Output

Name:

Name: Section:

Date:

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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
// Employee.java // Employee abstract superclass. public abstract class Employee { private String firstName; private String lastName; private String socialSecurityNumber; // three-argument constructor public Employee( String first, String last, String ssn ) { firstName = first; lastName = last; socialSecurityNumber = ssn; } // end three-argument Employee constructor // set first name public void setFirstName( String first ) { firstName = first; } // end method setFirstName // return first name public String getFirstName() { return firstName; } // end method getFirstName // set last name public void setLastName( String last ) { lastName = last; } // end method setLastName // return last name public String getLastName() { return lastName; } // end method getLastName

Fig. L 10.1

| Employee

abstract superclass. (Part 1 of 2.)

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

316

Object-Oriented Programming: Polymorphism

Chapter10

Prelab Activities Programming Output

Name:

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

// set social security number public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; // should validate } // end method setSocialSecurityNumber // return social security number public String getSocialSecurityNumber() { return socialSecurityNumber; } // end method getSocialSecurityNumber // return String representation of Employee object public String toString() { return String.format( "%s %s\nsocial security number: %s", getFirstName(), getLastName(), getSocialSecurityNumber() ); } // end method toString // abstract method overridden by subclasses public abstract double earnings(); // no implementation here } // end abstract class Employee | Employee

Fig. L 10.1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

abstract superclass. (Part 2 of 2.)

// SalariedEmployee.java // SalariedEmployee class extends Employee. public class SalariedEmployee extends Employee { private double weeklySalary; // four-argument constructor public SalariedEmployee( String first, String last, String ssn, double salary ) { super( first, last, ssn ); // pass to Employee constructor setWeeklySalary( salary ); // validate and store salary } // end four-argument SalariedEmployee constructor // set salary public void setWeeklySalary( double salary ) { weeklySalary = salary < 0.0 ? 0.0 : salary; } // end method setWeeklySalary // return salary public double getWeeklySalary() { return weeklySalary; } // end method getWeeklySalary // calculate earnings; override abstract method earnings in Employee public double earnings() { | SalariedEmployee

Fig. L 10.2

class derived from Employee. (Part 1 of 2.)

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

317

Prelab Activities Programming Output

Name:

31 32 33 34 35 36 37 38 39 40

return getWeeklySalary(); } // end method earnings // return String representation of SalariedEmployee object public String toString() { return String.format( "salaried employee: %s\n%s: $%,.2f", super.toString(), "weekly salary", getWeeklySalary() ); } // end method toString } // end class SalariedEmployee | SalariedEmployee

Fig. L 10.2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

class derived from Employee. (Part 2 of 2.)

// CommissionEmployee.java // CommissionEmployee class extends Employee. public class CommissionEmployee extends Employee { private double grossSales; // gross weekly sales private double commissionRate; // commission percentage // five-argument constructor public CommissionEmployee( String first, String last, String ssn, double sales, double rate ) { super( first, last, ssn ); setGrossSales( sales ); setCommissionRate( rate ); } // end five-argument CommissionEmployee constructor // set commission rate public void setCommissionRate( double rate ) { commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0; } // end method setCommissionRate // return commission rate public double getCommissionRate() { return commissionRate; } // end method getCommissionRate // set gross sales amount public void setGrossSales( double sales ) { grossSales = ( sales < 0.0 ) ? 0.0 : sales; } // end method setGrossSales // return gross sales amount public double getGrossSales() { return grossSales; } // end method getGrossSales

Fig. L 10.3

| CommissionEmployee

class derived from Employee. (Part 1 of 2.)

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

318

Object-Oriented Programming: Polymorphism

Chapter10

Prelab Activities Programming Output

Name:

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

// calculate earnings; override abstract method earnings in Employee public double earnings() { return getCommissionRate() * getGrossSales(); } // end method earnings // return String representation of CommissionEmployee object public String toString() { return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", "commission employee", super.toString(), "gross sales", getGrossSales(), "commission rate", getCommissionRate() ); } // end method toString } // end class CommissionEmployee | CommissionEmployee

Fig. L 10.3

class derived from Employee. (Part 2 of 2.)

27. What is output by the following code segment? Assume that the code appears in the main method of an application.
1 2 3 4 5 6 7 8
SalariedEmployee employee1 = new SalariedEmployee( "June", "Bug", "123-45-6789", 1000.00 ); CommissionEmployee employee2 = new CommissionEmployee( "Archie", "Tic", "987-65-4321", 15000.00, 0.10 ); System.out.printf( "Employee 1:\n%s\n\n", employee1 ); System.out.printf( "Employee 2:\n%s\n\n", employee2 );

Your answer:

28. What is output by the following code segment? Assume that the code appears in the main method of an application.
1 2 3 4 5 6 7 8
Employee firstEmployee = new SalariedEmployee( "June", "Bug", "123-45-6789", 1000.00 ); Employee secondEmployee = new CommissionEmployee( "Archie", "Tic", "987-65-4321", 15000.00, 0.10 ); System.out.printf( "Employee 1:\n%s\n\n", firstEmployee ); System.out.printf( "Employee 2:\n%s\n\n", secondEmployee );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

319

Prelab Activities Programming Output
Your answer:

Name:

29. What is output by the following code segment? Assume that the code follows the statements in Programming Output Exercise 28.
1 2
SalariedEmployee salaried = ( SalariedEmployee ) firstEmployee; System.out.printf( "salaried:\n%s\n", salaried );

Your answer:

30. What is output by the following code segment? Assume that the code follows the statements in Programming Output Exercise 29.
1 2
CommissionEmployee commission = ( CommissionEmployee ) firstEmployee; System.out.println( "commission:\n%s\n", commission );

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

321

Prelab Activities Correct the Code
Correct the Code

Name:

Name: Section:

Date:

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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

322

Object-Oriented Programming: Polymorphism

Chapter10

Prelab Activities Correct the Code

Name:

31. The following concrete class should inherit from abstract class Employee. A TipWorker is paid by the hour plus their tips for the week.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// TipWorker.java public final class TipWorker extends Employee { private double wage; // wage per hour private double hours; // hours worked for week private double tips; // tips for the week public TipWorker( String first, String last, double wagePerHour, double hoursWorked, double tipsEarned ) { super( first, last ); // call superclass constructor setWage ( wagePerHour ); setHours( hoursWorked ); setTips( tipsEarned ); } // set the wage public void setWage( double wagePerHour ) { wage = ( wagePerHour < 0 ? 0 : wagePerHour ); } // set the hours worked public void setHours( double hoursWorked ) { hours = ( hoursWorked >= 0 && hoursWorked < 168 ? hoursWorked : 0 ); } // set the tips public void setTips( double tipsEarned ) { tips = ( tipsEarned < 0 ? 0 : tipsEarned ); } } // end class TipWorker

Your answer:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

323

Prelab Activities Correct the Code

Name:

32. The following code should define method toString of class TipWorker in Correct the Code Exercise 31.
1 2 3 4 5 6 7
// return a string representation of a TipWorker public String toString() { return String.format( "Tip worker: %s\n%s: $%,.2f; %s: %.2f; %s: $%,.2f\n", toString(), "hourly wage", wage, "hours worked", hours, "tips earned", tips ); }

Your answer:

33. The following code should input information about five TipWorkers from the user and then print that information and all the TipWorkers’ calculated earnings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// Test2.java import java.util.Scanner; public class Test2 { public static void main( String args[] ) { Employee employee[]; Scanner input = new Scanner( System.in ); for ( int i = 0; i < employee.length; i++ ) { System.out.print( "Input first name: " ); String firstName = input.nextLine(); System.out.print( "Input last name: " ); String lastName = input.nextLine(); System.out.print( "Input hours worked: " ); double hours = input.nextDouble(); System.out.print( "Input tips earned: " ); double tips = input.nextDouble(); employee[ i ] = new Employee( firstName, lastName, 2.63, hours, tips ); System.out.printf( "%s %s earned $%.2f\n", employee[ i ].getFirstName(), employee[ i ].getLastName(), employee[ i ].earnings() ); input.nextLine(); // clear any remaining characters in the input stream } // end for } // end main } // end class Test2

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

324

Object-Oriented Programming: Polymorphism

Chapter10

Prelab Activities Correct the Code
Your answer:

Name:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

325

Lab Exercises
Lab Exercise 1 — Payroll System Modification
Name: Section: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 10.4–Fig. L 10.5) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Date:

Lab Objectives
• • •

This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Seventh Edition. In this lab, you will practice: Creating a new class and adding it to an existing class hierarchy. Using the updated class hierarchy in a polymorphic application. Understanding polymorphism.

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

(Payroll System Modification) Modify the payroll system of Figs. 10.4–10.9 to include an additional Employee subclass PieceWorker that represents an employee whose pay is based on the number of pieces of merchandise produced. Class PieceWorker should contain private instance variables wage (to store the employee’s wage per piece) and pieces (to store the number of pieces produced). Provide a concrete implementation of method earnings in class PieceWorker that calculates the employee’s earnings by multiplying the number of pieces produced by the wage per piece. Create an array of Employee variables to store references to objects of each concrete class in the new Employee hierarchy. For each Employee, display its string representation and earnings.

Description of the Problem

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

326

Object-Oriented Programming: Polymorphism

Chapter10

Lab Exercises

Name:

Lab Exercise 1 — Payroll System Modification
Sample Output
Employees processed polymorphically: salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 earned $800.00 hourly social hourly earned employee: Karen Price security number: 222-22-2222 wage: $16.75; hours worked: 40.00 $670.00

commission employee: Sue Jones social security number: 333-33-3333 gross sales: $10,000.00; commission rate: 0.06 earned $600.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 earned $500.00 piece worker: Rick Bridges social security number: 555-55-5555 wage per piece: $2.25; pieces produced: 400 earned $900.00

Program Template
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Lab Exercise 1: PieceWorker.java // PieceWorker class extends Employee. public class PieceWorker extends Employee { /* declare instance variable wage */ /* declare instance variable pieces */ // five-argument constructor public PieceWorker( String first, String last, String ssn, double wagePerPiece, int piecesProduced ) { /* write code to initialize a PieceWorker */ } // end five-argument PieceWorker constructor // set wage /* write a set method that validates and sets the PieceWorker's wage */ // return wage /* write a get method that returns the PieceWorker's wage */ // set pieces produced /* write a set method that validates and sets the number of pieces produced */

Fig. L 10.4 |

PieceWorker.java.

(Part 1 of 2.)

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

327

Lab Exercises

Name:

Lab Exercise 1 — Payroll System Modification

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

// return pieces produced /* write a get method that returns the number of pieces produced */ // calculate earnings; override abstract method earnings in Employee public double earnings() { /* write code to return the earnings for a PieceWorker */ } // end method earnings // return String representation of PieceWorker object public String toString() { /* write code to return a string representation of a PieceWorker */ } // end method toString } // end class PieceWorker PieceWorker.java.

Fig. L 10.4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

(Part 2 of 2.)

// Lab Exercise 1: PayrollSystemTest.java // Employee hierarchy test program. public class PayrollSystemTest { public static void main( String args[] ) { // create five-element Employee array Employee employees[] = new Employee[ 5 ]; // initialize array with Employees employees[ 0 ] = new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 ); employees[ 1 ] = new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 ); employees[ 2 ] = new CommissionEmployee( "Sue", "Jones", "333-33-3333", 10000, .06 ); employees[ 3 ] = new BasePlusCommissionEmployee( "Bob", "Lewis", "444-44-4444", 5000, .04, 300 ); /* create a PieceWoker object and assign it to employees[ 4 ] */ System.out.println( "Employees processed polymorphically:\n" ); // generically process each element in array employees for ( Employee currentEmployee : employees ) { System.out.println( currentEmployee ); // invokes toString System.out.printf( "earned $%,.2f\n\n", currentEmployee.earnings() ); } // end for } // end main } // end class PayrollSystemTest PayrollSystemTest.java

Fig. L 10.5 |

Problem-Solving Tips
1. The PieceWorker constructor should call the superclass Employee constructor to initialize the employee’s name.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

328

Object-Oriented Programming: Polymorphism

Chapter10

Lab Exercises

Name:

Lab Exercise 1 — Payroll System Modification
2. The number of pieces produced should be greater than or equal to 0. Place this logic in the set method for the pieces variable. 3. The wage should be greater than or equal to 0. Place this logic in the set method for the wage variable. 4. The main method must explicitly create a new PieceWorker object and assign it to an element of the employees array. 5. If you have any questions as you proceed, ask your lab instructor for assistance.

Follow-Up Question and Activity
1. Explain the line of code in your PayrollSystemTest’s main method that calls method earnings. Why can that line invoke method earnings on every element of the employees array?

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

329

Lab Exercises

Name:

Lab Exercise 2 — Accounts Payable System Modification
Lab Exercise 2 — Accounts Payable System Modification

Name: Section:

Date:

This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 10.6–Fig. L 10.9) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up question. The source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.

Lab Objectives
• •

This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Seventh Edition. In this lab you will practice: Provide additional polymorphic processing capabilities to an inheritance hierarchy by implementing an interface. Using the instanceof operator to determine whether a variable refers to an object that has an is-a relationship with a particular class. Comparing interfaces and abstract classes.

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

(Accounts Payable System Modification) In this exercise, we modify the accounts payable application of Figs. 10.11–10.15 to include the complete functionality of the payroll application. The application should still process two Invoice objects, but now should process one object of each of the four Employee subclasses (Figs. 10.5–10.8). If the object currently being processed is a BasePlusCommissionEmployee, the application should increase the BasePlusCommissionEmployee’s base salary by 10%. Finally, the application should output the payment amount for each object. Complete the following steps to create the new application: a) Modify classes HourlyEmployee and CommissionEmployee to place them in the Payable hierarchy as subclasses of the version of Employee that implements Payable (Fig. 10.13). [Hint: Change the name of method earnings to getPaymentAmount in each subclass so that the class satisfies its inherited contract with interface Payable.] b) Modify class BasePlusCommissionEmployee such that it extends the version of class CommissionEmployee created in Part a.

Description of the Problem

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

330

Object-Oriented Programming: Polymorphism

Chapter10

Lab Exercises

Name:

Lab Exercise 2 — Accounts Payable System Modification
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
Invoices and Employees processed polymorphically: invoice: part number: 01234 (seat) quantity: 2 price per item: $375.00 payment due: $750.00 invoice: part number: 56789 (tire) quantity: 4 price per item: $79.95 payment due: $319.80 salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 payment due: $800.00 hourly employee: Karen Price social security number: 222-22-2222 hourly wage: $16.75; hours worked: 40.00 payment due: $670.00 commission employee: Sue Jones social security number: 333-33-3333 gross sales: $10,000.00; commission rate: 0.06 payment due: $600.00 base-salaried commission employee: Bob Lewis social security number: 444-44-4444 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 new base salary with 10% increase is: $330.00 payment due: $530.00

Program Template
1 2 3 4 5 6 7 8
// Lab Exercise 2: HourlyEmployee.java // HourlyEmployee class extends Employee, which implements Payable. public class HourlyEmployee extends Employee { private double wage; // wage per hour private double hours; // hours worked for week

Fig. L 10.6 |

HourlyEmployee.java.

(Part 1 of 2.)

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 10

Object-Oriented Programming: Polymorphism

331

Lab Exercises

Name:

Lab Exercise 2 — Accounts Payable System Modification

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

// five-argument constructor public HourlyEmployee( String first, String last, String ssn, double hourlyWage, double hoursWorked ) { super( first, last, ssn ); setWage( hourlyWage ); // validate and store hourly wage setHours( hoursWorked ); // validate and store hours worked } // end five-argument HourlyEmployee constructor // set wage public void setWage( double hourlyWage ) { wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage; } // end method setWage // return wage public double getWage() { return wage; } // end method getWage // set hours worked public void setHours( double hoursWorked ) { hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked

Similar Documents

Free Essay

Java Server Pages Assignment

...iii. All questions are compulsory. iv. Submission should be made online through the upload link available in the UMS. Q1. What are the various implicit objects available in JSP? Explain each of them with an example. Ans: Implicit Objects In any JSP Page, there are a bunch of implicit objects that are available for the programmer to use. It contains a variety of information that can be used to display stuff on the page. In this chapter, we are going to look at the following JSP Implicit Objects that are available for a programmer.  • request • response • out • session • config • application • page • pageContext So, Lets get Started!!!  JSP Implicit Objects The JSP Implicit objects mentioned in the list in the previous paragraph are available by means of automatically defined variables. These variables have the same name and case as the list above. In the forthcoming paragraphs we will be looking at them one by one.  request This is the HttpServletRequest instance associated with the client request. As you know, the data between the Servlet and the JSP flows by using the HttpServletRequest and the HttpServletResponse objects. The page receives a request and sends a response. The data sent by a JSP page is available in the request in the Servlet and similarly the data sent by the servlet is available in the JSP again in the request object. There is a surprising amount of information stored in it. For example, you can get the request type (whether it is...

Words: 2737 - Pages: 11

Premium Essay

A Java Applet Paper

...A Java Applet Paper BY DuWoyn Snipe A Java applet is an applet delivered to the users in the form of Java bytecode. Java applets can run in a web browser using a Java Virtual Machine or Sun’s Applet Viewer, a stand-alone tool for testing applets. What this means is that is that it is own program language that is different than JavaScript, but we will get into that later on. Java applet is program language that is written in different types of bytecode, other than just the normal Java language, it is also written in Jython, JRuby, or Eiffel. Now the Java applet that I found is http://www.schubart.net/rc / which is a simple Rubik’s Cube Applet that allows you to play with the Rubik’s Cube. The way that it allows you to play is by at first scrambling the cube, then you gets to try and rebuild it back. Now it keeps track of how many moves that you do in order to try and figure it out. The controls for the Rubik’s Cube are very simple in the fact that the mouse is how you make the cube move. Now you can see that as you play with it the Rubik’s Cube moves very fast to the point that you almost don’t see it change. This is due to the fact that the Java applet is much faster than normal JavaScript by about 2011 times. Now this is a big deal if you are going to be running 3D graphics for the fact that they will run in real time and not slow down in order to load. Now with that last part in mind I believe that Java applet enhances a website for the fact that it allows for much...

Words: 487 - Pages: 2

Free Essay

Web 238 Team Assignment

...Javascript Creating a Website and presenting it online to users across the world has become a regular occurrence over the past few decades. Web pages belong to companies with services to sell, and others, to individuals with information to share. The basic Web site is built with HTML, and then creatively enhanced with CSS. To create a visually expressive Web site that can attract thousands of visitors each day you need to use more than HTML and decide what the site contains. There are different languages that can be used to add a sense of style to your site, some of the possible devices are JavaScript, Java, DOM, and AJAX. In the following paper our team will discuss a few examples of how each can be used in Web development. Comparison of Java and JavaScript Java and JavaScript are both object-oriented languages (Burns, 2012). Knowing how to use one language often becomes confusing when attempting to learn the other. Some of the differences between the two are that Java applets can create stand-alone applications that work across platforms running as standalone programs. However, JavaScript cannot create these stand-alone applications and reside on an Internet browser. A programmer must compile Java code before the program can run. This requires an outside program just to compile the code. A compiler turns Java code into machine language code before a browser can interpret it. Any changes the programmer makes to the code will require him to recompile the program...

Words: 2442 - Pages: 10

Premium Essay

Sport

...Computer Science What is java? Java is an object-oriented language, which is a type of programming in which programmers define both the data type of a data structure and the type of operations that can be applied to the data structure. There are more languages that are object-oriented for example C++ and Pascal. Java is very similar to C++ but has been simplified to eliminate language features that cause common errors in the program. Java was designed to be like C++ but easier to use so it had the ‘look and feel’ but simpler to use Java is commonly used foundations for developing and delivering content on the web. There are more than 9 million Java developers world-wide and more than 3 billion phones run on java. Java can be used to create complete applications that may run on a single computer or be distributed among servers and the clients in a network. Another use of java is it can be used to build a small application module or more commonly known as an applet for use as part of a web page. This allows interaction with the page. What is IDE? Integrated development environment (IDE) is a programming environment integrated into a software application that provides a GUI (Graphical User Interface) builder, text or code editor, a complier (this analyses and executes each line of source code (look below for a diagram)) and/or interpreter (This executes instructions written in a high level language (Java, C++, etc.) and a debugger (This is a program that finds errors...

Words: 365 - Pages: 2

Premium Essay

Java

...JMaster list of Java interview questions - 115 questions By admin | July 18, 2005 115 questions total, not for the weak. Covers everything from basics to JDBC connectivity, AWT and JSP. 1. What is the difference between procedural and object-oriented programs?- a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code. 2. What are Encapsulation, Inheritance and Polymorphism?- Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions. 3. What is the difference between Assignment and Initialization?- Assignment can be done as many times as desired whereas initialization can be done only once. 4. What is OOPs?- Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling 5. access to code. What are Class, Constructor...

Words: 6762 - Pages: 28

Premium Essay

My It Report

...MICHAEL OKPARA UNIVERSITY OF AGRICULTURE, UMUDIKE P.M.B 7267, UMUAHIA, ABIA STATE. A TECHNICAL REPORT ON A SIX MONTHS STUDENT INDUSTRIAL WORK EXPERIENCE CARRIED OUT AT ASHPOT MICROSYSTEMS LIMITED, 142 MARKET ROAD ABA. BY ELEANYA IFEANYICHI FAVOUR MOUAU/BSC/10/11/2222 SUBMITTED TO THE DEPARTMENT OF COMPUTER SCIENCE IN PARTIAL FULFILMENT FOR THE AWARD OF BACHELOR OF SCIENCE (BSc) DEGREE IN COMPUTER SCIENCE. DECEMBER 2013 DECLARATION I ELEANYA IFEANYICHI FAVOUR with the matriculation number MOUAU/BSc/10/11/2222, hereby declare that I underwent six months of industrial training at ASHPOT MICROSYSTEMS LIMITED, 142 market road Aba and that this report is written by me to the best of practical knowledge acquired during the course of the training program. DEDICATION This report is dedicated to God almighty for his grace upon my life and for seeing me through in the course of my industrial training, and to my wonderful family for their tireless support, love, and advice up to this point of academic pursuit. CERTIFICATION We the undersigned hereby certified that ELEANYA IFEANYICHI FAVOUR with the registration number MOUAU/BSC/10/2222, has duly completed her six months Industrial Training at Ashpot Microsystem Limited Aba, in partial fulfillment of the requirements for the award of Bachelor of Science (B.Sc...

Words: 1843 - Pages: 8

Free Essay

Java Tutorials

...The Java™ Web Services Tutorial For Java Web Services Developer’s Pack, v2.0 February 17, 2006 Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.U.S. Government Rights - Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and its supplements. This distribution may include materials developed by third parties. Sun, Sun Microsystems, the Sun logo, Java, J2EE, JavaServer Pages, Enterprise JavaBeans, Java Naming and Directory Interface, EJB, JSP, J2EE, J2SE and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. Unless otherwise licensed, software code in all technical materials herein (including articles, FAQs, samples) is provided under this License. Products covered by and information contained in this service manual are controlled by U.S. Export Control laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited. DOCUMENTATION IS PROVIDED "AS IS" AND ALL EXPRESS OR...

Words: 55069 - Pages: 221

Free Essay

Test Bank Data Structure and Java

...Test Bank for Data Structures with Java John R. Hubbard Anita Huray University of Richmond Chapter 1 Object-Oriented Programming Answer “True” or “False”: 1. An analysis of the profitability of a software solution would be done as part of the feasibility study for the project. 2. The best time to write a user manual for a software solution is during its maintenance stage. 3. The requirements analysis of a software project determines what individual components (classes) will be written. 4. In a large software project it is preferable to have the same engineers write the code as did the design. 5. In the context of software development, “implementation” refers to the actual writing of the code, using the design provided. 6. Software engineers use “OOP” as an acronym for “organized operational programming”. 7. The term “Javadoc” refers to the process of “doctoring” Java code so that it runs more efficiently. 8. Software engineers use “UML” as an acronym for “Unified Modeling Language”. 9. UML diagrams are used to represent classes and the relationships among them. 10. The “is-a” relationship between classes is called composition. 11. The “contains-a” relationship between classes is called aggregation. 12. The “has-a” relationship between classes is called inheritance. 1 Test Bank 2 13. A “mutable” class is one whose objects can be modified by the objects of other classes. 14...

Words: 1904 - Pages: 8

Premium Essay

Java and Java Script

...and lastly to the Internet, one thing has been a constant, different languages evolved based on a need. For these two languages, the Internet was a perfect fit, and without them the Internet would be a less dynamic and vibrant highway. As the Internet grew, more and more people found it a more viable place to do business. With that came a need for languages that were fairly easy to learn, dynamic, secure, portable, and maintainable. The industry answered that call with languages such as Java and JavaScript. This paper will perform an analysis of both Java and JavaScript. In order for the reader to gain a better understanding of these languages, the history of these languages with overviews will be presented along with a discussion of the benefits and drawbacks. The History of Java In the middle of May 1995 Java was introduced into the world, and along with Netscape it would be the new way for Internet users to access this new information superhighway. But before it got to this point, Java technology was developed almost by accident. Back in 1991, Sun Microsystems was looking into the future in anticipation of the future of computing, and they tasked a team that became know as the “Green Project”. Their main focus was to come up with a plan for the future of computing, but what they came out with was something quite unexpected. Under the guidance of James Gosling, a team was locked away in an external site to work on the project that would define Sun’s technology direction...

Words: 1329 - Pages: 6

Premium Essay

Java Programming and Inheritance

...Muhammad 1 Mikey Muhammad Date Class Mr.Radev Java Programming and Inheritance As time continues to pass, the world we now live in is dominated by the use of technology. Technology continues to advance, and it seems, as if we can’t function without it. Whether it’s the use of technology in school or work, it is everywhere and you cannot escape it. It is important for us to be able to adapt to it and learn how the new inventions work and function properly. The Internet for example is one of the most important aspects of life today. The Internet allows us to have access to everything, and have endless information at our fingertips, whether it’s through a computer screen or through the use of a cellular device, or even a watch. Some of us choose to only use this amazing tool that has been provided to us, and then some us choose to go more in depth with this tool we call the Internet and want to know how it works. Although it takes millions of programs and concepts and other factors to get the Internet working how it does, the focus of my term paper will be Inheritance in Java. In order to truly understand what the specifics of Java are, you have to start with the totality of the Java program. The Java language could easily be the most difficult to understand because there are so many components to how it works. Java is a programing language and computing platform, which is a huge part of making the Internet work. It was first released by Sun Microsystems in 1995. Without...

Words: 1332 - Pages: 6

Premium Essay

Hostel

...Chapter-1 1.1 Introduction Android is an software platform and operating system for mobile devices. It is based on the Linux kernel. It was developed by Google and later the Open Handset Alliance (OHA). It allows writing managed code in the Java language. Due to Android here is the possibility to write applications in other languages and compiling it to ARM native code. Unveiling of the Android platform was announced on 5 November 2007 with the founding of OHA. It's a consortium of several companies 1.1.1 Introduction to Project Environment OPERATING SYSTEM: An operating system (OS) is software consisting of programs and data hostel management system project report runs on computers and manages computer hardware resources and provides common services for efficient execution of various application software. For hardware functions such as input and output and memory allocation, the operating system acts as an intermediary between application programs and the computer hardware, although the application code is usually executed directly by the hardware and will frequently call the OS or be interrupted by it. Operating systems | | Common Features: * Process management * Interrupts * Memory management ...

Words: 15019 - Pages: 61

Premium Essay

Intro to Programming Unit 1 Research Assignment

...Unit 1 research assignment 1 1970’s 1) Pascal, Creator, Niklaus Wirth. The specific motivation behind this language was to encourage good programming practice using structured programming and data structuring. 2) SQL (Structured Query Language) designed by, Donald D. Chamberlin, and Raymond F. Boyce. The motivation behind this language was designed for managing data held in a relational database management system. ( RDBMS) 3) C, Designed by Dennis Ritchie. the motivation behind this language is structured programming and allows lexical variable scope and recursion. 4) Applesoft BASIC, developed by Marc McDonald, and Ric Weiland. The motivation with this language was it was designed to be backwards-compatible with integer BASIC and used the core of Microsoft’s 6502 BASIC implementation. 5) GRASS, Developed by Thomas A. DeFanti. GRASS is similar to BASIC in sytax, but added numerous instructions for specifying 2D object animation, including scaling, translation, rotation and color changes over time. 1980’s 1) BASICA, Designed by Thomas E. Kurtz. Designed to offer support for the graphics and sound hardware of the IBM PC line. 2) Turbo Pascal, developed by Borland, under Philippe Kahn’s leadership. This is a software development system that includes a compiler and an integrated development environment for the Pascal programming language. 3) C++, designed by Bjarne Stroustrup. This is a general purpose programming language that is free-form...

Words: 677 - Pages: 3

Free Essay

Wp7 for Android

... About this Document 4 Target Audience 4 Conventions Used in this Document 4 Chapter 1: Introducing Windows Phone 7 Platform to Android Application Developers 5 The Developer Tools 5 Windows Phone 7 Architecture 5 Comparing the Programming Stack of Windows Phone 7 with Android 7 Summary 11 Related Resources 11 Chapter 2: User Interface Guidelines 12 Designing the Application Interface 13 Application User Interface Design 14 Comparing Windows Phone 7 and Android Navigation 18 Windows Phone 7 Frame and Page Structure 19 Application Templates 21 Summary 21 Related Resources 21 Chapter 3: The Developer and Designer Tools 23 A Comparison of Android and Windows Phone 7 Tools 23 Development Life Cycle and Windows Phone 7 Developer Tools 24 The UI Design Tools 26 Building Applications 33 Debugging 34 Summary 38 Chapter 4: C# programming 39 Managed Programming 40 A Comparison between C# Features and Java Classes 41 A Comparison of Important Class Libraries 51 The New features of C# 54 Comparing API Documentation Tools 58 NDoc 58 NDocs vs. Javadoc 61 Summary 61 Related Resources 62 Chapter 5: A Comparison of Application Life Cycles in Windows Phone 7 and Android 63 Multitasking in Android and Windows Phone 7 63 Tombstoning of Applications in Windows Phone 7 64 Life Cycle of a Windows Phone 7 Application 64 Role of Handlers in an Application’s Life Cycle 66 Comparing Life-cycle Methods 68 Tombstoning...

Words: 19181 - Pages: 77

Free Essay

Java

...Eclipse and Java for Total Beginners Tutorial Companion Document Eclipse And Java For Total Beginners Companion Tutorial Document By Mark Dexter Table of Contents Introduction........................................................................................................... .............................2 . Tutorial Target Audience.....................................................................................................................2 Tutorial Objectives..............................................................................................................................2 Why learn Java with Eclipse?.............................................................................................................3 Topics Covered...................................................................................................................................3 Tutorial Approach............................................................................................................... ................3 . Getting The Most From This Tutorial..................................................................................................3 Sample Java Application – Personal Lending Library........................................................................4 Downloading and Installing Eclipse ...................................................................................................4 Playing the Lessons...........................

Words: 7556 - Pages: 31

Free Essay

Customer Track System

...on job posting and job searching. This application helps the company helps to place qualified and eligible candidates. Any company can put their advertisement in this site, so that they improve their sales and viewers will get more information about the company. They will be charged to put their advertisements. What is JAVA ? Java is an entire programming language resembling C or C++. It takes a sophisticated programmer to create Java code. And it requires a sophisticated programmer to maintain it. With Java, you can create complete applications. Or you can attach a small group of instructions, a Java "applet" that improves your basic HTML. A Java Applet can also cause text to change color when you roll over it. A game, a calendar, a scrolling text banner can all be created with Java Applets. There are sometimes compatibility problems between Java and various browsers, operating systems or computers, and if not written correctly, it can be slow to load. Java is a powerful programming language with excellent security, but you need to be aware of the tradeoffs. What is JSP ? Short for Java Server Page. A server-side technology, Java Server Pages are an...

Words: 1170 - Pages: 5