f86da2ed377b3c6

63
8/10/2019 f86da2ed377b3c6 http://slidepdf.com/reader/full/f86da2ed377b3c6 1/63  CPCS 203 Lab sheet 4 Student Name: _____________________________ Section: __ King Abdulaziz University Faculty of Computing and Information Systems Spring Term 2012/1433 Course Code: CPCS-203 Course Name: Programming II  _________________________________________________________________  _____ Objectives In this chapter you will learn:  The concept of polymorphism.  To use overridden methods to effect polymorphism.  To distinguish between abstract and concrete classes.  To declare abstract methods to create abstract classes.  How polymorphism makes systems extensible and maintainable.  To determine an object’s type at execution time.   To declare and implement interfaces.

Upload: jesusfreaktech

Post on 02-Jun-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 1/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

King Abdulaziz UniversityFaculty of Computing and Information Systems

Spring Term 2012/1433

Course Code: CPCS-203 Course Name:

Programming II _________________________________________________________________  _____

Objectives

In this chapter you will learn:

  The concept of polymorphism.

  To use overridden methods to effect polymorphism.

  To distinguish between abstract and concrete classes.

  To declare abstract methods to create abstract classes.  How polymorphism makes systems extensible and maintainable.

  To determine an object’s type at execution time. 

  To declare and implement interfaces.

Page 2: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 2/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Prelab Activity: 

Matching

The questions are intended to test and reinforce your understanding of key concepts. You may answerthe questions before the lab.

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

Term Description

I 1. abstract method  a) Can be used in place of an abstract class when thereis no default implementation to inherit. 

J 2. getClass method   b) Indicates that a method cannot be overridden orthat a class can- not be a su per class. 

H 3 . implements keyword c) Class method which returns the name of the classassociated with the Class object.

L 4 . type-wrapper classes  d) An operator that returns true if its left operand (avariable of a reference type) has the is-a relationshipwith its right operand (a class or interface name).

F 5 . downcasting  e) Uses superclass references to manipulate sets ofsubclass objects in a generic manner.

K 6 . concrete class  f) Casting a superclass reference to a subclassreference.

E 7 . polymorphism  g) Cannot be instantiated; used primarily forinheritance.

D 8 . instanceof   h) Indicates that a class will declare each method inan interface with the signature specified in theinterface declaration.

B 9 . final i) Must be overridden in a subclass; otherwise, the

subclass must be declared abstract.

C 10. getName method  j) Returns an object that can be used to determineinformation about the object’s class. 

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

Page 3: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 3/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

A 12. interface  l) Classes in the java.lang package that are used tocreate objects containing values of primitive types.

Page 4: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 4/63

Page 5: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 5/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Prelab Activity: 

Short Answers

10. Describe the concept of polymorphism.

Polymorphism makes it possible to design and implement systems that are more easilyextensible. Programs can be written to process objects generically as one type, and newclasses can be added with little or no modifications to the generic part of the program. Forexample, a program can be designed to draw shapes rather than to draw rectangles, ovalsand lines. Each shape object would know how to draw itself.

11. Define what it means to declare a method final and what it means to declare a classfinal.

Declaring a method final means that the method cannot be overridden in a subclass.Declaring a class final means that it cannot be a superclass (i.e., a class cannot inherit froma final class). Methods in a final class are implicitly final.

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

A compilation error occurs in this case. Every method in the interface must beimplemented, or the class must be declared abstract to prevent this compilation error.

13. Describe how to determine the class name of an object’s class. 

Call method getClass on an object to obtain an object of type Class that represents the

object’s type. Then call the Class object’s getName method to get a String containing theclass’s name. 

Page 6: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 6/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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

An abstract class can be used as a superclass and to declare variables that can storereferences to objects of the abstract class’s subclass. An abstract class cannot be used to

create objects. A concrete class can be used to create objects and declare variables. Inaddition, a concrete class can also be used as a superclass as long as it is not declared final.

Page 7: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 7/63

Page 8: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 8/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

42 // set social security number 43 public void setSocialSecurityNumber( String ssn ) 44 { 45 socialSecurityNumber  = ssn; // should validate 46 } // end method setSocialSecurityNumber 47 

48 // return social security number 49 public String getSocialSecurityNumber() 50 { 51 return socialSecurityNumber; 52 } // end method getSocialSecurityNumber 53 

54 // return String representation  of Employee object 55 public String toString() 56 { 57 return String.format(  "%s %s\nsocial  security number: %s", 58 getFirstName(), getLastName(), getSocialSecurityNumber() ); 59 } // end method toString 60 

61 // abstract method  overridden by subclasses 

62 public abstract double earnings();  // no implementation here 63 } // end abstract  class Employee 

Fig. 1 | Employee abstr act superclass. (Part 2 of 2)

1 // SalariedEmployee.java 2 // SalariedEmployee class extends Employee. 3 

4 public class SalariedEmployeeextends Employee 5 { 6 private double weeklySalary; 7 

8 // f our-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 { 

31 return getWeeklySalary(); 32 } // end method earnings 33 

Page 9: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 9/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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

Fig. 2 | SalariedEmployee class derived from Employee.

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 // f ive-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; 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 

Page 10: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 10/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

49 public String toString() 50 { 51 return String.format(  "%s: %s\n%s: $%,.2f;  %s:  %.2f", 52 "commission employee",  super.toString(), 53 "gross sales",  getGrossSales(), 54 "commission rate",  getCommissionRate()  ); 55 } // end method toString 

56 } // end class CommissionEmployee 

Fig. 3 | CommissionEmployee class derived from Employee.

15.  What is output by the following code segment? Assume that the code appears in the main method of an

ap- plication. 

1 SalariedEmployee employee1 = 2 new SalariedEmployee( "June",  "Bug",  "123-45-6789",  1000.00 ); 3 

4 CommissionEmployee employee2 = 5 new CommissionEmployee(  "Archie",  "Tic",  "987-65-4321",  15000.00,  0.10 ); 6 

7 System.out.printf(  "Employee 1:\n%s\n\n",  employee1 ); 8 System.out.printf(  "Employee 2:\n%s\n\n",  employee2 ); 

Your an swer : 

Employee 1: salaried employee: June Bug social security number:  123-45-6789 weekly  salary: $1,000.00 

Employee 2: commission employee:  Archie Tic social security number:  987-65-4321 gross sales: $15,000.00; commission rate: 0.10 

16.  What is output by the following code segment? Assume that the code appears in the main method of an

ap- plication. 

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 ); 

7 System.out.printf(  "Employee 1:\n%s\n\n",  firstEmployee ); 8 System.out.printf(  "Employee 2:\n%s\n\n",  secondEmployee ); 

Page 11: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 11/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Your an swer : 

Employee 1: salaried employee: June Bug social security number:  123-45-6789 weekly  salary: $1,000.00

 

Employee 2: commission employee:  Archie Tic social security number:  987-65-4321 gross sales: $15,000.00; commission rate: 0.10 

17.  What is output by the following code segment? Assume that the code follows the statements in Pr o g rammin g  

Output Exer ci se 28. 

1 SalariedEmployee salaried = ( SalariedEmployee ) firstEmployee; 

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

Your an swer : 

salaried: salaried employee: June Bug social security number:  123-45-6789 weekly  salary: $1,000.00 

18.  What is output by the following code segment? Assume that the code follows the statements in Pr o g rammin g  

Output Exer ci se 17 . 

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

Your an swer :

Although the cast in line 1 is allowed at compile time, this results in a ClassCastException at run- time because a SalariedEmployee is not a CommissionEmployee. 

Exception in thread "main" java.lang.ClassCastException:

SalariedEmployee at Test.main(Test.java:17) 

Page 12: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 12/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Prelab Activity: 

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 compilation error, circle the error in the program andwrite the corrected code in the s pace  provided after each problem. If the code does notcontain an error, write ―no er ror.‖ [ Not e: There may be more than one error in each programsegment.] 

 For que stions  19 – 33 assume the following d e finit ion  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 f irstName  = 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 

Page 13: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 13/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

19.  The following concrete class should inherit from abstract class Employee. A TipWorker is paid by the

hour plus their tips for the week. 

1 // TipWorker.java 2 public final class TipWorker extends Employee 3 { 

4 private double wage; // wage per hour 5 private double hours; // hours worked f or  week 6 private double tips; // tips f or  the week 7 

8 public TipWorker( String  first, String last, 9 double wagePerHour, double hoursWorked, double tipsEarned ) 

10 { 11 super(  first, last ); // call superclass constructor 12 setWage ( wagePerHour ); 13 setHours( hoursWorked ); 14 setTips( tipsEarned  ); 15 } 16 

17 // set the wage 

18 public void setWage( double wagePerHour ) 19 { 20 wage = ( wagePerHour  < 0 ? 0 : wagePerHour ); 21 } 22 

23 // set the hours worked 24 public void setHours( double hoursWorked ) 25 { 26 hours = ( hoursWorked >= 0 && hoursWorked < 168 ? hoursWorked : 0 ); 27 } 28 

29 // set the tips 30 public void setTips( double tipsEarned  ) 31 { 32 tips = ( tipsEarned  < 0 ? 0 : tipsEarned ); 

33 } 34 } // end class TipWorker 

Your an swer : 

Class TipWorker did not implement abstract method earnings that was inherited from class Employee. The class must implement this method to be a concrete class. 

1 // TipWorker.java 2 public final class TipWorker extends Employee 3 { 4 private double wage; // wage per hour 

5 private double hours; // hours worked f or  week 6 private double tips; // tips f or  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 } 

Page 14: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 14/63

Page 15: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 15/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

21.  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 // 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 f or 32 } // end main 33 } // end class Test2 

Your an swer : 

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[] = new Employee[ 5 ]; 

9 Scanner input=

new Scanner(  System.in ); 10 

11 for ( int i = 0;  i < employee.length;  i++ ) 12 { 13 System.out.print(  "\nInput 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: " ); 

Page 16: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 16/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

20 double hours = input.nextDouble(); 21 

22 System.out.print(  "Input tips earned: " ); 23 double tips = input.nextDouble(); 24 

25 employee[  i ] = new TipWorker( 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 f or 32 } // end main 33 } // end class Test2 

Page 17: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 17/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Lab Exercises: 

Lab Exercise 1  —  Payroll System Modification

This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The

 problem is divided into six par ts: 

1. Lab O b jectives 

2. Description of the Problem 

3. Sample Out put 

4. Program Template (Fig. L 4 – Fig. 5) 

5. Problem-Solving Tips 

6. Follow-Up Question and Activity 

The program template represents a complete working Java program, with one or more key lines of code replacedwith comments. Read the problem description and examine the sample output; then study the template code.Using the problem-solving t ips 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. Thesource code for the template is available at www.pearsonhighered.com/deitel. 

Lab Objectives 

This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: 8/e. 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. 

Descr iption of the Problem 

(Payroll System Modification) Modify the  payroll system of Figs. 4 – 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) andpieces (to store the number of pieces produced). Provide a concrete implementation of method earnings in class

PieceWorker that calculates the em ployee’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 newEmployee hierarchy. For each Employee, display its string representation and earnings. 

Page 18: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 18/63

Page 19: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 19/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __25 // return pieces produced 

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

28 // calculate earnings; override abstract  method earnings in Employee 29 public double earnings() 30 { 31 /* write code to return the earnings for a PieceWorker */ 

32 } // end method earnings 33 

34 // return String representation  of PieceWorker object 35 public String toString() 36 { 37 /* write code to return a string representation of a PieceWorker */ 

38 } // end method toString 39 } // end class PieceWorker 

Fig. 4 | PieceWorker.java. (Par t 2 of 2.) 

1 // Lab Exercise 1: PayrollSystemTest.java 2 // Employee hierarchy test program. 3 

4 public class PayrollSystemTest 5 { 6 public static void main( String  args[] ) 7 { 8 // create five-element Employee array 9 Employee employees[]  = new Employee[ 5 ]; 10 

11 // initialize array with Employees 12 employees[ 0 ] = new SalariedEmployee( 13 "John",  "Smith",  "111-11-1111",  800.00 ); 14 employees[ 1 ] = new HourlyEmployee( 15 "Karen",  "Price",  "222-22-2222",  16.75,  40 ); 16 employees[ 2 ] = new CommissionEmployee( 17 "Sue",  "Jones",  "333-33-3333",  10000,  .06 ); 18 employees[ 3 ] = new BasePlusCommissionEmployee( 19 "Bob",  "Lewis",  "444-44-4444",  5000,  .04,  300 ); 

20 /* create a PieceWoker object and assign it to  employees[ 4 ] */ 21 

22 System.out.println( "Employees processed polymorphically:\n" ); 23 

24 // generically process each element in array employees 25 for ( Employee currentEmployee : employees ) 26 { 27 System.out.println( currentEmployee ); // invokes toString 28 System.out.printf( 29 "earned $%,.2f\n\n",  currentEmployee.earnings() ); 30 } // end f or 31 } // end main 32 } // end class PayrollSystemTest 

Fig. 5 | PayrollSystemTest. java 

Page 20: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 20/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Solution 

1 // Lab Exercise 1: PieceWorker 2 // PieceWorker class extends Employee. 3 

4 public class PieceWorker extends Employee 5 { 6 private double wage; // wage per piece 

7 private int pieces;  // pieces of merchandise produced in week 8 

9 // f ive-argument  constructor 10 public PieceWorker( String first, String  last, String ssn, 11 double wagePerPiece,  int piecesProduced ) 12 { 13 super(  first, last, ssn ); 14 setWage( wagePerPiece  ); // validate and store wage per  piece 15 setPieces( piecesProduced ); // validate and store pieces produced 16 } // end five-argument PieceWorker constructor 17 

18 // set wage 19 public void setWage( double wagePerPiece  ) 20 { 21 wage = ( wagePerPiece  < 0.0 ) ? 0.0 : wagePerPiece;

 22 } // end method setWage 23 

24 // return wage 25 public double getWage() 26 { 27 return wage; 28 } // end method getWage 29 

30 // set pieces produced 31 public void setPieces( int piecesProduced ) 32 { 33 pieces  = ( piecesProduced < 0 ) ? 0 : piecesProduced; 34 } // end method setPieces 35 

36 // return pieces produced 37 public int getPieces() 38 { 39 return pieces; 40 } // end method getPieces 41 

42 // calculate earnings; override abstract  method earnings in Employee 43 public double earnings() 44 { 45 return getPieces() * getWage(); 46 } // end method earnings 47 

48 // return String representation  of PieceWorker object 49 public String toString() 50 {

 51 return String.format(  "%s: %s\n%s: $%,.2f;  %s:  %d", 52 "piece worker",  super.toString(), 53 "wage per piece",  getWage(),  "pieces produced",  getPieces() ); 54 } // end method toString 55 } // end class PieceWorker 

Page 21: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 21/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __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 employees[ 4 ] = new PieceWorker( 21 "Rick",  "Bridges",  "555-55-5555",  2.25,  400 ); 22 

23 System.out.println( "Employees processed polymorphically:\n" ); 24 

25 // generically process each element in array employees 26 for ( Employee currentEmployee : employees ) 27 { 28 System.out.println( currentEmployee ); // invokes toString 29 System.out.printf( 30 "earned $%,.2f\n\n",  currentEmployee.earnings() ); 31 } // end f or 32 } // end main 33 } // end class PayrollSystemTest 

Problem-Solving Tips 

1. The PieceWorker constructor should call the superclass Employee constructor to initialize the employ- ee’s

name. 

2. The number of pieces produced should be greater than or equal to 0. Place this logic in the  set method for thepieces 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 canthat line invoke method earnings on every element of the employees array? 

This line of code uses polymorphism to  ensure that each Employee’s  earnings is calculated correctly. Everyelement of array employees refers to an object that is an Employee. Since class Employee declares an abstract

earnings method, every concrete subclass of Employee must implement the earnings method. Also, sinceobjects can be created only from concrete classes, it is guaranteed that the object to which currentEmployee

refers during an iteration of the for statement will have an earnings method. 

Page 22: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 22/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Lab Exercises: 

Lab Exercise 2 —  Accounts Paya ble System Modif ication 

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 par ts: 

1. Lab O b jectives 

2. Description of the Problem 

3. Sample Out put 

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 replacedwith comments. Read the problem description and examine the sample output; then study the template code.

Using the  problem-solving tips as a guide, replace the/* */

comments with Java code. Compile and execute 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.pearsonhighered.com/deitel. 

Lab Objectives 

This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: 8/e. In this lab you will pr actice: 

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

  Using the instanceof operator to determine whether avariable refers to an object that has an is-a relationshipwith a particular class. 

The follow-up question and activity will also give you practice:  Comparing interfaces and abstract classes. 

Descr iption of the Problem 

(Accounts Payable System Modi f icat ion) In this   e x e r c i s e , we modify the accounts payableapplication of Figs. 11 – 15 to include the complete functionality of the  payroll application. The applicationshould still  process two Invoice  objects, but now should  process one object of each of the four Employee

subclasses  (Figs. 5 – 8). If the object currently being  processed is a BasePlusCommissionEmployee, theapplication should increase the BasePlusCommissionEmployee’s  base salary  by 10%. Finally, the applicationshould 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. 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. 

c) Modify PayableInterfaceTest to  polymorphically process two Invoices,  one SalariedEmployee, oneHourlyEmployee, one CommissionEmployee  and one BasePlusCommissionEmployee. First output a stringrepresentation of each Payable object. Next, if an object is a BasePlusCommissionEmployee, increase its base salary

 by 10%. Finally, output the payment amount for each Payable object. 

Page 23: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 23/63

Page 24: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 24/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

9 // f ive-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 /* write a method header to satisfy the Payable interface */ 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. 6 | HourlyEmployee.java. (Par t 2 of 2.) 

Page 25: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 25/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 // f ive-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 /* write a method header to satisfy the Payable interface */ 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. 7 | CommissionEmployee.java. 

Page 26: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 26/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __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 /* write a method header to satisfy the Payable interface */ 31 { 32  /* calculate and return the BasePlusCommissionEmployee's earnings */ 

33 } // end method getPaymentAmount 34 

35 // return String representation  of BasePlusCommissionEmployee object 36 public String toString() 37 { 38 return String.format(  "%s %s;  %s: $%,.2f", 

39 "base-salaried",  super.toString(), 40 "base salary",  getBaseSalary()  ); 41 } // end method toString 42 } // end class BasePlusCommissionEmployee 

Fig. 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. 9 | PayableInterfaceTest.java. (Par t 1 of 2.) 

Page 27: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 27/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __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 /* create an HourlyEmployee object */ 18 payableObjects[  4 ] = 

19 /* create a CommissionEmployee  object */ 

20 payableObjects[  5 ] = 21 /* create a BasePlusCommissionEmployee object */ 22 

23 System.out.println( 24 "Invoices and Employees  processed polymorphically:\n" ); 25 

26 // generically process each element in array payableOb jects 27 for ( Payable currentPayable : payableObjects ) 28 { 29 // output currentPayable and its appropriate payment  amount 30 System.out.printf(  "%s \n",  currentPayable.toString()  ); 31 

32 /* write code to determine whether currentPayable is  a 33 BasePlusCommissionEmployee object */ 34 {

 35 

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

37 } // end if  38 

39 System.out.printf(  "%s: $%,.2f\n\n", 40 "payment due",  currentPayable.getPaymentAmount() ); 41 } // end f or 42 } // end main 43 } // end class PayableInterfaceTest 

Fig. 9 | PayableInterfaceTest.java. (Par t 2 of 2.) 

Solution 

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 f or  week 8 

9 // f ive-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 

Page 28: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 28/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __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 public double getPaymentAmount() 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 

Page 29: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 29/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 // f ive-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 public double getPaymentAmount() 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 

Page 30: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 30/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

1 // Lab Exercise 2: BasePlusCommissionEmployee.java 2 // BasePlusCommissionEmployee class extends CommissionEmployee. 

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 public double getPaymentAmount() 31 { 

32 return getBaseSalary() + super.getPaymentAmount(); 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 

Page 31: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 31/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 

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 new HourlyEmployee(  "Karen",  "Price",  "222-22-2222",  16.75,  40 ); 18 payableObjects[  4 ] = 19 new CommissionEmployee( 20 "Sue",  "Jones",  "333-33-3333",  10000,  .06 ); 21 payableObjects[  5 ] = 22 new BasePlusCommissionEmployee( 

23 "Bob",  "Lewis",  "444-44-4444",  5000,  .04,  300 ); 24 

25 System.out.println( 26 "Invoices and Employees  processed polymorphically:\n" ); 27 

28 // generically process each element in array payableOb jects 29 for ( Payable currentPayable : payableObjects ) 30 { 31 // output currentPayable and its appropriate payment  amount 32 System.out.printf(  "%s \n",  currentPayable.toString()  ); 33 

34 if ( currentPayable instanceof BasePlusCommissionEmployee ) 35 { 36 // downcast Payable reference to 37 // BasePlusCommissionEmployee reference 38 BasePlusCommissionEmployee employee = 39 ( BasePlusCommissionEmployee ) currentPayable; 40 

41 double  oldBaseSalary = employee.getBaseSalary(); 42 employee.setBaseSalary( 1.10 * oldBaseSalary ); 43 System.out.printf( 44 "new  base salary with  10%% increase is: $%,.2f\n", 45 employee.getBaseSalary()  ); 46 } // end if  47 

48 System.out.printf(  "%s: $%,.2f\n\n", 49 "payment due",  currentPayable.getPaymentAmount() ); 50 } // end f or 51 } // end main 

52 } // end class PayableInterfaceTest 

Page 32: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 32/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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. 

A benefit of an abstract class is that you can declare the instance variables and methods that are required by allclasses in a hierarchy. Subclasses can then enhance the existing instance variables and methods inherited fromthe abstract class and override existing methods as necessary. This reduces the amount of code that must bewritten to create each new class in the hierarchy. This benefit of abstract classes is a disadvantage of inter-faces, which are not allowed to  provide any method implementations or instance variables. Thus, any class thatimplements an interface must define all the instance variables and methods necessary to properly satisfy the

requirements of the interface. A benefit of interfaces is that any class can implement an interface such that objects of that class can then be processed in a polymorphic program that uses variables of the interface type. This is particularly useful forextending existing systems. A disadvantage of abstract classes (and classes in general) is that a class can extend only one other class at a time.However, a class can implement multiple interfaces. 

Page 33: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 33/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Lab Exercises: 

Lab Exercise 3  —  Debugging

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

Sample Output 

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

Point: [7, 11]Area = 0.00 

Volume = 0.00 

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

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

Broken Code 

1 // Shape.java 2 // Definition of interface Shape 3 

4 public interface Shape 5 { 6 public abstract String getName();  // return shape name 7 } // end interface Shape 

Page 34: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 34/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 } 

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 

Page 35: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 35/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

1 // Circle.java 2 // Definition of class Circle 3 

4 public class Circle extends Point 

5 { 6 protected double radius; 

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 

Page 36: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 36/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

1 // Cylinder.java 2 // Definition of class Cylinder. 3 

4 public class Cylinder extends Circle 5 { 6 protected double height;  // height of Cylinder 

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 

Page 37: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 37/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 f or 

35 } // end main 36 } // end class Test 

Solution 

1 // Shape.java 2 // Definition of interface Shape 3 

4 public interface Shape 5 { 6 public abstract double area(); // calculate area 7 public abstract double volume();  // calculate volume 8 public abstract String getName();  // return shape name 

9 } // end interface Shape 

Page 38: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 38/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 } 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 

Page 39: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 39/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

1 // Circle.java 2 // Definition of class Circle 3 

4 public class Circle extends Point 5 { 

6 protected double radius; 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 

Page 40: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 40/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

1 // Cylinder.java 2 // Definition of class Cylinder. 3 

4 public class Cylinder extends Circle 5 { 6 protected double height;  // height of Cylinder 7 

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 

Page 41: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 41/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 Shape arrayOfShapes[]  = new Shape[ 3 ]; // create Shape array 15 

16 // aim arrayOfShapes[  0 ] at subclass Point object 17 arrayOfShapes[ 0 ] = point; 18 

19 // aim arrayOfShapes[  1 ] at subclass Circle object 20 arrayOfShapes[ 1 ] = circle; 

21 22 // aim arrayOfShapes[  2 ] at subclass Cylinder object 23 arrayOfShapes[ 2 ] = 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 f or 35 } // end main

 36 } // end class Test 

List of Errors 

  Shape.java: The Shape interface must declare public abstract methods area and volume.   Test.java, line 14: The array should be of type Shape so that the array elements can refer to Point,

Circle and Cylinder objects for polymorphic processing.   Test.java, line 17: Once the array is changed to type Shape, it is not necessary to cast point to a dif-

ferent type — a Point object can always be assigned to a Shape variable based on the hierarchy defined inthis exercise.

  Test.java, line 20: Once the array is changed to type Shape, it is not necessary to cast circle to a dif-ferent type — a Circle object can always be assigned to a Shape variable based on the hierarchy defined in

this exercise.  Test.java, line 23: The cast operation is unnecessary — a Cylinder object can always  be assigned to a

Shape variable based on the hierarchy defined in this exercise. 

Page 42: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 42/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Postlab Activities 

Coding Exercises

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

 For each of the following  pr obl em s , write a program or a program segment that performs the specified action. 

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

1 // Shape.java 2 // Shape class declaration. 3 

4 public abstract class Shape 5 { 

6 } // end class Shape 

2.  In the class from Coding Exer ci se 1, create a protected instance variable shapeName of type String, and write

an accessor method getName for obtaining its value. 

1 // Shape.java 2 // Shape class declaration. 3 

4 public abstract class Shape 5 { 6 protected String shapeName; 7 

8 public String getName() 

9 { 10 return shapeName; 11 } 12 } // end class Shape 

3.  In the class of Coding Exer ci se 2, define an abstract method getArea that returns a double representationof a specific shape’s area. Subclasses of this class must implement getArea to calculate a specific shape’s area. 

1 // Shape.java 2 // Shape class declaration. 3 

4 public abstract class Shape 5 { 

6 protected String shapeName; 7 

8 // abstract getArea method must  be implemented by concrete subclasses 9 public abstract double getArea(); 10 

11 public String getName() 12 { 13 return shapeName; 14 } 15 } // end class Shape 

Page 43: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 43/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

4.  Define a class Square that inherits from class Shape from Coding  Exer ci se 3; it should contain an instance

variable side, which  represents the length of a side of the square. Provide a constructor that takes oneargument 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". 

1 // Square.java 

2 // Definition of class Square. 3 

4 public class Square extends Shape 5 { 6 private double side; 7 

8 // constructor 9 public Square(  double s ) 10 { 11 side = ( s < 0 ? 0 : s ); 12 shapeName = "Square"; 13 } 14 } // end class Square 

5.  The Square class from Coding Exerci se 4 should implement the getArea method of its abstract su perclass;

this implementation should compute the area of the square and return the result. 

1 // Square.java 2 // Definition of class Square. 3 

4 public class Square extends Shape 5 { 6 private double side; 7 

8 // constructor 9 public Square(  double s ) 10 { 

11 side = ( s < 0 ? 0 : s ); 12 shapeName = "Square"; 13 } 14 

15 // return the area of a Square 16 public double getArea() 17 { 18 return side * side; 19 } 20 } // end class Square 

Page 44: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 44/63

Page 45: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 45/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

8.  Write an application that tests the Square and Rectangle classes from Coding Exer ci se s 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. 

1 // TestArea.java 

2 import  java.util.Scanner; 3 

4 public class TestArea 5 { 6 public static void main( String  args[] ) 7 { 8 Scanner input = new Scanner(  System.in ); 9 

10 System.out.print( "Input  the side of the square: " ); 11 double side = input.nextDouble(); 12 

13 System.out.print( "Input  the length of the rectangle: " ); 14 double length = input.nextDouble(); 15 

16 System.out.print( "Input  the width of   the rectangle: " ); 

17 double width = input.nextDouble(); 18 

19 Shape arrayOfShapes[]  = new Shape[ 2 ]; 20 arrayOfShapes[ 0 ] = new Square( side ); 21 arrayOfShapes[ 1 ] = new Rectangle( length, width  ); 22 

23 for ( Shape shape : arrayOfShapes ) 24 System.out.printf(  "The %s has an area of %.2f\n",  shape.getName(), 25 shape.getArea()  ); 26 } // end main 27 } // end class TestArea 

Input  the side of the square:  10.5 Input  the length of the rectangle: 2.5 Input  the width of the rectangle: 3.5 The Square has an area of 110.25 The Rectangle has an area of 8.75 

Page 46: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 46/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

Postlab Activities 

Programming Challenges 

The Programming C hall en ge s are more involved than the Coding Exerci se s and may require a significant amount of

time to complete. Write a Java program for each of the problems in this section. The answers to these problems areavailable at www.pearsonhighered.com/deitel. Pseudocode, hints or sample outputs  are  provided for each problem to aid you in your programming. 

9.  (Payroll System  M odification )  Modify the  payroll system of Figs. 10.4 – 10.9 to include private instance

variable birthDate in class Employee. Use class Date of Fig. 8.7 to represent an employee’s  birthday. Add

 get methods to class Date and replace method toDateString with method toString. Assume that payroll is

 processed once per month. Create an array of Employee variables to store references to the various

employee objects. In a loop, calculate the  payroll for each Employee (polymorphically), and add a $100.00

 bonus to the person’s  payroll amount if the current month is the month in which the Employee’s birthdayoccurs. 

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 socialsecurity number:  333-33-3333 birth date:  9/8/1954 gross sales: $10,000.00; commission rate: 0.06earned: $600.00 

base-salaried  commission employee:  Bob Lewissocial 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 pa ge... ) 

Page 47: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 47/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 socialsecurity 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 Lewissocial 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 SalariedEmployeeEmployee 1 is a HourlyEmployeeEmployee 2 is a CommissionEmployee Employee 3 is a BasePlusCommissionEmployee 

Solution 

1 // Programming Challenge  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 private Date birthDate; 10 

11 // six-argument constructor 12 public Employee( String  first, String last,  String  ssn, 13 int month, int day, int year  ) 14 { 15 f irstName  = first; 

16 lastName  = last; 17 socialSecurityNumber  = ssn; 18 birthDate  = new Date( month,  day, year ); 19 } // end six-argument Employee constructor 20 

21 // set first name 22 public void setFirstName( String  first ) 23 { 24 f irstName  = first; 

Page 48: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 48/63

Page 49: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 49/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

1 // Programming Challenge  1: Date. java 2 // Date class declaration  with get  methods added. 3 

4 public class Date 5 { 6 private int month;  // 1-12 

7 private int day;  // 1-31 based on month 8 private int year; // any year 9 

10 // constructor:  call checkMonth to confirm proper  value f or  month; 11 // call  checkDay to confirm proper value for day 12 public Date( int theMonth, int theDay, int theYear ) 13 { 14 month  = checkMonth( theMonth ); // validate month 15 year = theYear; // could validate year 16 day = checkDay( theDay ); // validate day 17 

18 System.out.printf( 19 "Date object  constructor for date %s\n", toString() ); 20 } // end Date constructor 

21 

22 // utility  method to confirm proper month  value 23 private int checkMonth(  int testMonth ) 24 { 25 if ( testMonth > 0 && testMonth <= 12 ) // validate month 26 return testMonth; 27 else // month  is invalid 28 { 29 System.out.printf(  "Invalid month (%d) set to 1.\n",  testMonth ); 30 return 1; // maintain ob ject  in consistent state 31 } // end else 32 } // end method checkMonth 33 

34 // utility  method to confirm proper day value based on month  and year 35 private int checkDay( int testDay ) 

36 { 37 int daysPerMonth[] = 38 { 0,  31,  28,  31,  30,  31,  30,  31,  31,  30,  31,  30,  31 }; 39 

40 // check if day in range for month 41 if ( testDay > 0 && testDay <= daysPerMonth[ month ] ) 42 return testDay; 43 

44 // check f or  leap year 45 if ( month == 2 && testDay == 29 && ( year % 400 == 0 || 46 ( year  % 4 == 0 && year  % 100 != 0 ) ) ) 47 return testDay; 48 

49 System.out.printf( "Invalid day (%d) set to 1.\n",  testDay ); 

50 

51 return 1; // maintain object in consistent state 52 } // end method checkDay 53 

54 // return day 55 public int getDay() 56 { 57 return day; 58 } // end method getDay 

Page 50: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 50/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

59 

60 // return month 61 public int getMonth() 62 { 63 return month; 64 } // end method getMonth 

65 66 // return year 67 public int getYear() 68 { 69 return year; 70 } // end method getYear 71 

72 // return a String of the form month/day/year 73 public String toString() 74 { 75 return String.format(  "%d/%d/%d",  month,  day, year ); 76 } // end method toString 77 } // end class Date 

1 // Programming Challenge  1: SalariedEmployee.java 2 // SalariedEmployee class derived from Employee. 3 

4 public class SalariedEmployee extends Employee 5 { 6 private double weeklySalary; 7 

8 // seven-argument constructor 9 public SalariedEmployee( String  first, String last, String  ssn, 10 int month, int day, int year,  double salary ) 11 { 12 super(  first, last, ssn, month,  day, year ); 13 setWeeklySalary( salary ); 14 } // end seven-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 { 31 return getWeeklySalary(); 32 } // end method earnings 33 

34 // return String representation  of SalariedEmployee object 35 public String toString() 36 { 

Page 51: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 51/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 // Programming Challenge  1: HourlyEmployee.java 2 // HourlyEmployee class derived  f rom  Employee. 3 

4 public class HourlyEmployee extends Employee 5 { 6 private double wage; // wage per hour 7 private double hours; // hours worked f or  week 8 

9 // eight-argument constructor 10 public HourlyEmployee( String first, String last,  String ssn, 11 int month, int day, int year, 12 double hourlyWage, double hoursWorked )

 13 { 14 super(  first, last, ssn, month,  day, year ); 15 setWage( hourlyWage ); 16 setHours( hoursWorked ); 17 } // end eight-argument  HourlyEmployee constructor 18 

19 // set wage 20 public void setWage( double hourlyWage ) 21 { 22 wage = hourlyWage < 0.0 ? 0.0  : hourlyWage; 23 } // end method setWage 24 

25 // return wage 26 public double getWage() 

27 { 28 return wage; 29 } // end method getWage 30 

31 // set hours worked 32 public void setHours( double hoursWorked ) 33 { 34 hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ? 35 hoursWorked : 0.0; 36 } // end method setHours 37 

38 // return hours worked 39 public double getHours() 40 { 41 return hours; 42 } // end method getHours 43 

44 // calculate earnings; override abstract  method earnings in Employee 45 public double earnings() 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 earnings 52 

Page 52: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 52/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 

1 // Programming Challenge  1: CommissionEmployee.java 2 // CommissionEmployee  class derived from Employee. 3 

4 public class CommissionEmployee  extends Employee 5 { 6 private double grossSales; // gross weekly sales 7 private double commissionRate; // commission percentage 8 

9 // eight-argument constructor 10 public CommissionEmployee( String first, String last, String ssn, 11 int month, int day, int year,  double sales, double rate ) 

12 { 13 super(  first, last, ssn, month,  day, year ); 14 setGrossSales( sales ); 15 setCommissionRate( rate ); 16 } // end eight-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; override abstract  method earnings in Employee 43 public double earnings() 44 { 45 return getCommissionRate() * getGrossSales(); 46 } // end method earnings 47 

Page 53: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 53/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

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 // Programming Challenge  1: BasePlusCommissionEmployee.java 2 // BasePlusCommissionEmployee class derived  from CommissionEmployee. 3 

4 public class BasePlusCommissionEmployee extends CommissionEmployee 5 { 6 private double baseSalary; // base salary per week 7 

8 // nine-argument constructor 9 public BasePlusCommissionEmployee( String  first, String last, 

10 String ssn,  int month,  int day, int year, 11 double sales, double rate, double salary ) 12 { 13 super(  first, last, ssn, month,  day, year, sales, rate ); 14 setBaseSalary( salary ); 15 } // end nine-argument BasePlusCommissionEmployee constructor 16 

17 // set base salary 18 public void setBaseSalary( double salary ) 19 { 20 baseSalary  = salary < 0.0 ? 0.0 : salary; // non-negative 21 } // end method setBaseSalary 22 

23 // return base salary 24 public double getBaseSalary() 25 { 26 return baseSalary; 27 } // end method getBaseSalary 28 

29 // calculate earnings; override method earnings in CommissionEmployee 30 public double earnings() 31 { 32 return getBaseSalary() + super.earnings(); 33 } // end method earnings 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 

Page 54: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 54/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

1 // Programming Challenge  1: PayrollSystemTest.java 2 // Employee hierarchy test program. 3 import  java.util.Scanner; // program uses Scanner to  obtain user input 4 

5 public class PayrollSystemTest 6 { 

7 public static void main( String  args[] ) 8 { 9 // create subclass objects 10 SalariedEmployee salariedEmployee = 11 new SalariedEmployee( 12 "John",  "Smith",  "111-11-1111",  6,  15,  1944,  800.00 ); 13 HourlyEmployee  hourlyEmployee = 14 new HourlyEmployee( 15 "Karen",  "Price",  "222-22-2222",  12,  29,  1960,  16.75,  40 ); 16 CommissionEmployee commissionEmployee = 17 new CommissionEmployee( 18 "Sue",  "Jones",  "333-33-3333",  9,  8,  1954,  10000,  .06  ); 19 BasePlusCommissionEmployee basePlusCommissionEmployee = 20 new BasePlusCommissionEmployee( 

21 "Bob",  "Lewis",  "444-44-4444",  3,  2,  1965,  5000,  .04,  300 ); 22 

23 System.out.println( "Employees processed individually:\n" ); 24 

25 System.out.printf( "%s\n%s: $%,.2f\n\n", 26 salariedEmployee,  "earned",  salariedEmployee.earnings() ); 27 System.out.printf( "%s\n%s: $%,.2f\n\n", 28 hourlyEmployee, "earned",  hourlyEmployee.earnings() ); 29 System.out.printf( "%s\n%s: $%,.2f\n\n", 30 commissionEmployee, "earned",  commissionEmployee.earnings()  ); 31 System.out.printf( "%s\n%s: $%,.2f\n\n", 32 basePlusCommissionEmployee, 33 "earned",  basePlusCommissionEmployee.earnings() ); 34 

35 // create four-element Employee array 

36 Employee employees[]  = new Employee[ 4 ]; 37 

38 // initialize array with Employees 39 employees[ 0 ] = salariedEmployee; 40 employees[ 1 ] = hourlyEmployee; 41 employees[ 2 ] = commissionEmployee; 42 employees[ 3 ] = basePlusCommissionEmployee; 43 

44 Scanner input = new Scanner(  System.in ); // to get current month 45 int currentMonth; 46 

47 // get and validate current month 48 do 49 { 

50 System.out.print(  "Enter the current month (1 - 12):  " ); 51 currentMonth = input.nextInt(); 52 System.out.println(); 53 } while ( ( currentMonth < 1 ) || ( currentMonth > 12 ) ); 54 

55 System.out.println( "Employees processed polymorphically:\n" ); 56 

Page 55: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 55/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

57 // generically process each element in array employees 58 for ( Employee currentEmployee : employees ) 59 { 60 System.out.println( currentEmployee ); // invokes toString 61 

62 // determine whether element is a BasePlusCommissionEmployee 63 if ( currentEmployee instanceof BasePlusCommissionEmployee ) 64 { 65 // downcast Employee reference to 66 // BasePlusCommissionEmployee reference 67 BasePlusCommissionEmployee employee = 68 ( BasePlusCommissionEmployee ) currentEmployee; 69 

70 double  oldBaseSalary = employee.getBaseSalary(); 71 employee.setBaseSalary( 1.10 * oldBaseSalary ); 72 System.out.printf( 73 "new  base salary with  10%% increase is: $%,.2f\n", 74 employee.getBaseSalary()  ); 75 } // end if  76 

77 // if month  of employee's birthday, add $100 to salary 78 if ( currentMonth == currentEmployee.getBirthDate().getMonth()  ) 79 System.out.printf( 80 "earned  $%,.2f   %s\n\n",  currentEmployee.earnings(), 81 "plus  $100.00 birthday bonus"  ); 82 else 83 System.out.printf( 84 "earned  $%,.2f\n\n",  currentEmployee.earnings()  ); 85 } // end f or 86 

87 // get type name of each ob ject  in employees array 88 for ( int j = 0;  j < employees.length;  j++ ) 89 System.out.printf(  "Employee %d is  a %s\n",  j, 90 employees[ j ].getClass().getName() ); 

91 } // end main 92 } // end class PayrollSystemTest 

Page 56: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 56/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

10.  (Shape Hierarchy) Implement the Shape hierarchy shown in Fig. 9.3 of  Java How to Program. 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 ofthe 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 TwoDimensionalShape or a ThreeDimensionalShape. If a shape is aTwoDimensionalShape, display its area. If a shape is a ThreeDimensionalShape, display its area and volume. 

Hint: 

•  Your output should appear as follows: 

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

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

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

 Sphere's volume is 33 

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

Solution 

1 // Programming Challenge  2: Shape.java 2 // Definition of class Shape. 3 

4 public abstract class Shape 

5 { 6 private int x; // x coordinate 7 private int y; // y coordinate 8 

9 // two-argument  constructor 10 public Shape( int x, int y ) 11 { 12 this.x = x; 13 this.y = y; 14 } // end two-argument Shape constructor 15 

16 // set x coordinate 17 public void setX( int x ) 18 { 19 this.x = x; 

20 } // end method setX 21 

22 // set y coordinate 23 public void setY( int y ) 24 { 25 this.y = y; 26 } // end method setY 

Page 57: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 57/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

27 

28 // get x coordinate 29 public int getX() 30 { 31 return x; 32 } // end method getX 33 

34 // get y coordinate 35 public int getY() 36 { 37 return y; 38 } // end method getY 39 

40 // return String representation  of Shape object 41 public String toString() 42 { 43 return String.format(  "(%d, %d)",  getX(),  getY() ); 44 } 45 

46 // abstract methods 47 public abstract String getName(); 48 } // end class Shape 

1 // Programming Challenge  2: TwoDimensionalShape.java 2 // Definition of class TwoDimensionalShape. 3 

4 public abstract class TwoDimensionalShape extends Shape 5 { 6 private int dimension1; 7 private int dimension2; 8 

9 // f our-argument  constructor 10 public TwoDimensionalShape( int x, int y, int d1,  int d2 ) 11 { 12 super(  x, y ); 13 dimension1 = d1; 14 dimension2 = d2; 15 } // end four-argument TwoDimensionalShape constructor 16 

17 // set methods 18 public void setDimension1( int d ) 19 { 20 dimension1 = d; 21 } // end method setDimension1 22 

23 public void setDimension2( int d ) 24 { 25 dimension2 = d; 26 } // end method setDimension2 

27 28 // get methods 29 public int getDimension1() 30 { 31 return dimension1; 32 } // end method getDimension1 33 

Page 58: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 58/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

34 public int getDimension2() 35 { 36 return dimension2; 37 } // end method getDimension2 38 

39 // abstract method 40 public abstract int getArea(); 

41 } // end class TwoDimensionalShape 

1 // Programming Challenge  2: Circle.java 2 // Definition of class Circle. 3 

4 public class Circle extends TwoDimensionalShape 5 { 6 // three-argument  constructor 7 public Circle(  int x, int y, int radius) 8 {

 9 super(  x, y, radius,  radius ); 10 } // end three-argument  Circle constructor 11 

12 // overridden methods 13 public String getName() 14 { 15 return "Circle"; 16 } // end method getName 17 

18 public int getArea() 19 { 20 return ( int ) 21 ( Math.PI * getRadius() * getRadius() ); 22 } // end method getArea 

23 24 // set method 25 public void setRadius( int radius ) 26 { 27 setDimension1( radius ); 28 setDimension2( radius ); 29 } // end method setRadius 30 

31 // get method 32 public int getRadius() 33 { 34 return getDimension1(); 35 } // end method getRadius 36 

37 public String toString() 38 { 39 return String.format(  "%s %s:  %d\n", 40 super.toString(),  "radius",  getRadius() ); 41 } // end method toString 42 } // end class Circle 

Page 59: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 59/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

1 // Programming Challenge  2: Square.java 2 // Definition of class Square. 3 

4 public class Square extends TwoDimensionalShape 5 { 6 // three-argument  constructor 

7 public Square(  int x, int y, int side ) 8 { 9 super(  x, y, side, side ); 10 } // end three-argument  Square constructor 11 

12 // overridden methods 13 public String getName() 14 { 15 return "Square"; 16 } // end method getName 17 

18 public int getArea() 19 { 20 return getSide() * getSide(); 21 } // end method getArea

 22 

23 // set method 24 public void setSide( int side ) 25 { 26 setDimension1( side ); 27 setDimension2( side ); 28 } // end method setSide 29 

30 // get method 31 public int getSide() 32 { 33 return getDimension1(); 34 } // end method getSide 35 

36 public String toString() 37 { 38 return String.format(  "%s %s:  %d\n", 39 super.toString(),  "side",  getSide()  ); 40 } // end method toString 41 } // end class Square 

1 // Programming Challenge  2: ThreeDimensionalShape.java 2 // Definition of class ThreeDimensionalShape. 3 

4 public abstract class ThreeDimensionalShape extends Shape 5 { 6 private int dimension1; 

7 private int dimension2; 8 private int dimension3; 9 

10 // f ive-argument  constructor 11 public ThreeDimensionalShape( 12 int x, int y, int d1,  int d2,  int d3 ) 13 { 14 super(  x, y ); 15 dimension1 = d1; 

Page 60: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 60/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

16 dimension2 = d2; 17 dimension3 = d3; 18 } // end five-argument ThreeDimensionalShape constructor 19 

20 // set methods 21 public void setDimension1( int d ) 

22 { 23 dimension1 = d; 24 } // end method setDimension1 25 

26 public void setDimension2( int d ) 27 { 28 dimension2 = d; 29 } // end method setDimension2 30 

31 public void setDimension3( int d ) 32 { 33 dimension3 = d; 34 } // end method setDimension3 35 

36 // get methods 37 public int getDimension1() 

38 { 39 return dimension1; 40 } // end method getDimension1 41 

42 public int getDimension2() 43 { 44 return dimension2; 45 } // end method getDimension2 46 

47 public int getDimension3() 48 { 49 return dimension3; 50 } // end method getDimension3 

51 52 // abstract methods 53 public abstract int getArea(); 54 public abstract int getVolume(); 55 } // end class ThreeDimensionalShape 

1 // Programming Challenge  2: Sphere.java 2 // Definition of class Sphere. 3 

4 public class Sphere extends ThreeDimensionalShape 5 { 6 // three-argument  constructor 7 public Sphere(  int x, int y, int radius) 

8 { 9 super(  x, y, radius,  radius,  radius ); 10 } // end three-argument  Shape constructor 11 

12 // overridden methods 13 public String getName() 14 { 15 return "Sphere"; 16 } // end method getName 

Page 61: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 61/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

17 

18 public int getArea() 19 { 20 return ( int ) ( 4 * Math.PI * getRadius() * getRadius()  ); 21 } // end method getArea 22 

23 public int getVolume() 

24 { 25 return ( int ) ( 4.0  / 3.0 * Math.PI * 26 getRadius() * getRadius()  * getRadius() ); 27 } // end method getVolume 28 

29 // set method 30 public void setRadius( int radius ) 31 { 32 setDimension1( radius ); 33 setDimension2( radius ); 34 setDimension3( radius ); 35 } // end method setRadius 36 

37 // get method 38 public int getRadius()

 39 { 40 return getDimension1(); 41 } // end method getRadius 42 

43 public String toString() 44 { 45 return String.format(  "%s %s:  %d\n", 46 super.toString(),  "radius",  getRadius() ); 47 } // end method toString 48 } // end class Sphere 

1 // Programming Challenge  2: Cube. java 2 // Definition of class Cube. 3 

4 public class Cube extends ThreeDimensionalShape 5 { 6 // three-argument  constructor 7 public Cube( int x, int y, int side ) 8 { 9 super(  x, y, side, side, side ); 10 } // end three-argument  Cube constructor 11 

12 // overridden methods 13 public String getName() 14 { 15 return "Cube"; 16 } // end method getName 

17 18 public int getArea() 19 { 20 return ( int ) ( 6 * getSide() * getSide() ); 21 } // end method getArea 22 

23 public int getVolume() 24 { 

Page 62: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 62/63

 

CPCS 203 Lab sheet 4Student Name: _____________________________ Section: __

25 return ( int ) ( getSide()  * getSide()  * getSide() ); 26 } // end method getVolume 27 

28 // set method 29 public void setSide( int side ) 30 { 31 setDimension1( side ); 32 setDimension2( side ); 33 setDimension3( side ); 34 } // end method setSide 35 

36 // get method 37 public int getSide() 38 { 39 return getDimension1(); 40 } // end method getSide 41 

42 public String toString() 43 { 

44 return String.format(  "%s %s:  %d\n", 45 super.toString(),  "side",  getSide()  ); 46 } // end method toString 47 } // end class Cube 

1 // Programming Challenge  2: ShapeTest.java 2 // Program tests the Shape hierarchy. 3 

4 public class ShapeTest 5 { 6 // create Shape objects and display their  information 7 public static void main( String  args[] ) 8 { 9 Shape shapes[] = new Shape[ 4 ]; 10 shapes[ 0 ] = new Circle(  22,  88,  4 ); 11 shapes[ 1 ] = new Square( 71,  96,  10 ); 12 shapes[ 2 ] = new Sphere( 8,  89,  2 ); 13 shapes[ 3 ] = new Cube( 79,  61,  8 ); 14 

15 // call method print  on all shapes 16 for ( Shape currentShape : shapes ) 17 { 18 System.out.printf(  "%s: %s", 19 currentShape.getName(),  currentShape ); 20 

21 if ( currentShape instanceof TwoDimensionalShape ) 

22 { 23 TwoDimensionalShape twoDimensionalShape  = 24 ( TwoDimensionalShape ) currentShape; 25 

26 System.out.printf( "%s's area is %s\n", 27 currentShape.getName(), twoDimensionalShape.getArea() ); 28 } // end if  29 

30 if ( currentShape instanceof ThreeDimensionalShape ) 31 { 32 ThreeDimensionalShape threeDimensionalShape = 33 ( ThreeDimensionalShape ) currentShape; 

Page 63: f86da2ed377b3c6

8/10/2019 f86da2ed377b3c6

http://slidepdf.com/reader/full/f86da2ed377b3c6 63/63

CPCS 203 Lab sheet 4Student Name:_____________________________ Section:__

34 

35 System.out.printf( "%s's area is %s\n", 36 currentShape.getName(), threeDimensionalShape.getArea()  ); 37 System.out.printf( "%s's volume is %s\n", 38 currentShape.getName(), 

39 threeDimensionalShape.getVolume()  ); 40 } // end if  41 

42 System.out.println(); 43 } // end f or 44 } // end main 45 } // end class ShapeTest