King Abdulaziz University Fac

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.

Prelab Activity:
Matching

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

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

Term Description I1. abstractmethod a) Canbeusedinplaceofanabstractclasswhenthereisnodefault implementationto inherit. J2. getClassmethod b) Indicatesthatamethod cannotbeoverriddenor thataclasscan- notbeasuperclass.
H 3. implementskeyword
c) Class method which returns the name of the class associated with the Class object.
L 4. type-wrapperclasses
d) An operator that returns true if its left operand (a variable of a reference type) has the is-a relationship with its right operand (a class or interface name).
F5. downcasting
e) Uses superclass references to manipulate sets of subclass objects in a generic manner.
K6. concreteclass
f) Casting a superclass reference to a subclass reference.
E7. polymorphism
g) Cannot be instantiated; used primarily for inheritance.
D8. instanceof
h) Indicates that a class will declare each method in an interface with the signature specified in the interface declaration.
B9.final
i) Must be overridden in a subclass; otherwise, the subclass must be declared abstract.
C10.getNamemethod
j) Returns an object that can be used to determine information about the object’s class.
G 11.abstractclass k) A class that can be used to create objects. A12.interface
l) Classes in the java.lang package that are used to create objects containing values of primitive types.
Prelab Activity:
Fill in the Blank

Fill in the blanks for each of the following statements:

1. With polymorphism, it becomes possible to design and implement systems that are more extensible.
2. Although we cannot instantiate objects of abstract superclasses, we can declare references of abstract superclass types.
3. It is a syntax error if a class with one or more abstract methods is not explicitly declared abstract.
4. It is possible to assign a superclass reference to a subclass variable by downcasting the reference to the sub- class type.
5. A(n) interface may contain a set of public abstract methods and/or public static final fields.
6. When a method is invoked through a superclass reference to a subclass object, Java executes the version of the method found in the subclass .
7. The instanceofoperator determines whether the type of the object to which its left operand refers has an is-a relationship with the type specified as its right operand.
8. To use an interface, a class must specify that it implementsthe interface and must declare every method in the interface with the signatures specified in the interface declaration.
9. When a class implements an interface, it establishes an is-a relationship with the interface type.

Prelab Activity:
Short Answers

10. Describe the concept of polymorphism.
Polymorphism makes it possible to design and implement systems that are more easily extensible. Programs can be written to process objects generically as one type, and new classes can be added with little or no modifications to the generic part of the program. For example, a program can be designed to draw shapes rather than to draw rectangles, ovals and 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 class final.
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 from a 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 be implemented, 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 the class’s name.
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 store references 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. In addition, a concrete class can also be used as a superclass as long as it is not declared final.

Prelab Activity:
ProgrammingOutput

Foreachofthegivenprogramsegments,readthecodeandwritetheoutputinthespaceprovidedbeloweach program.[Note:Donotexecutetheseprogramsonacomputer.]
Usetheclassdefinitions inFig.1-Fig.3whenansweringProgrammingOutputExercises15-18.
1 // Employee.java
2 // Employee abstractsuperclass.
3
4 publicabstractclassEmployee
5 {
6 privateStringfirstName;
7 privateStringlastName;
8 privateStringsocialSecurityNumber;
9
10 // three-argumentconstructor
11 publicEmployee(Stringfirst,Stringlast,Stringssn )
12 {
13 firstName= first;
14 lastName= last;
15 socialSecurityNumber= ssn;
16 }// endthree-argumentEmployee constructor
17
18 // setfirst name
19 publicvoid setFirstName(Stringfirst)
20 {
21 firstName= first;
22 }// endmethodsetFirstName
23
24 // returnfirstname
25 publicStringgetFirstName()
26 {
27 returnfirstName;
28 }// endmethodgetFirstName
29
30 // setlastname
31 publicvoid setLastName(Stringlast)
32 {
33 lastName= last;
34 }// endmethodsetLastName
35
36 // returnlastname
37 publicStringgetLastName()
38 {
39 returnlastName;
40 }// endmethodgetLastName
41

Fig.1| Employeeabstractsuperclass. (Part 1 of 2)
42 // setsocialsecuritynumber
43 publicvoid setSocialSecurityNumber(String ssn )
44 {
45 socialSecurityNumber= ssn;// should validate
46 }// endmethodsetSocialSecurityNumber
47
48 // returnsocialsecuritynumber
49 publicStringgetSocialSecurityNumber()
50 {
51 returnsocialSecurityNumber;
52 }// endmethodgetSocialSecurityNumber
53
54 // returnStringrepresentationof Employee object
55 publicStringtoString()
56 {
57 returnString.format(“%s %snsocialsecuritynumber: %s”,
58 getFirstName(), getLastName(),getSocialSecurityNumber() );
59 }// endmethodtoString
60
61 // abstractmethodoverriddenby subclasses
62 publicabstractdouble earnings();// noimplementationhere
63 }// endabstractclassEmployee

Fig.1| Employeeabstractsuperclass. (Part 2 of 2)

1 // SalariedEmployee.java
2 // SalariedEmployeeclass extends Employee.
3
4 publicclass SalariedEmployeeextends Employee
5 {
6 privatedouble weeklySalary;
7
8 // four-argumentconstructor
9 publicSalariedEmployee(Stringfirst,Stringlast,Stringssn,
10 double salary)
11 {
12 super(first,last,ssn );// pass toEmployee constructor
13 setWeeklySalary(salary);// validateandstoresalary
14 }// endfour-argumentSalariedEmployee constructor
15
16 // setsalary
17 publicvoid setWeeklySalary(double salary)
18 {
19 weeklySalary= salary<0.0 ?0.0 :salary;
20 }// endmethodsetWeeklySalary

21
22 // returnsalary
23 publicdouble getWeeklySalary()
24 {
25 returnweeklySalary;
26 }// endmethodgetWeeklySalary
27
28 // calculate earnings;overrideabstractmethodearningsinEmployee
29 publicdouble earnings()
30 {

31 returngetWeeklySalary();
32 }// endmethodearnings
33
34 // returnStringrepresentationof SalariedEmployeeobject
35 publicStringtoString()
36 {
37 returnString.format(“salariedemployee:%sn%s: $%,.2f”,
38 super.toString(),”weeklysalary”,getWeeklySalary());
39 }// endmethodtoString
40 }// endclassSalariedEmployee

Fig.2| SalariedEmployee classderivedfromEmployee.
1 // CommissionEmployee.java
2 // CommissionEmployeeclassextends Employee.
3
4 publicclassCommissionEmployeeextends Employee
5 {
6 privatedouble grossSales;// gross weeklysales
7 privatedouble commissionRate;// commission percentage
8
9 // five-argumentconstructor
10 publicCommissionEmployee( Stringfirst,Stringlast, Stringssn,
11 double sales,double rate)
12 {
13 super(first,last,ssn );
14 setGrossSales(sales);
15 setCommissionRate(rate );
16 }// endfive-argumentCommissionEmployee constructor
17
18 // setcommission rate
19 publicvoid setCommissionRate(double rate)
20 {
21 commissionRate = (rate>0.0&&rate<1.0 )?rate:0.0;
22 }// endmethodsetCommissionRate
23
24 // returncommission rate
25 publicdouble getCommissionRate()
26 {
27 returncommissionRate;
28 }// endmethodgetCommissionRate
29
30 // setgross salesamount
31 publicvoid setGrossSales(double sales)
32 {
33 grossSales= (sales<0.0 )?0.0 :sales;
34 }// endmethodsetGrossSales
35
36 // returngross salesamount
37 publicdouble getGrossSales()
38 {
39 returngrossSales;
40 }// endmethodgetGrossSales
41

42 // calculate earnings;overrideabstractmethodearningsinEmployee
43 publicdouble earnings()
44 {
45 returngetCommissionRate()* getGrossSales();
46 }// endmethodearnings
47
48 // returnStringrepresentationof CommissionEmployeeobject
49 publicStringtoString()
50 {
51 returnString.format(“%s:%sn%s: $%,.2f;%s:%.2f”,
52 “commission employee”,super.toString(),
53 “grosssales”,getGrossSales(),
54 “commission rate”,getCommissionRate());
55 }// endmethodtoString
56 }// endclassCommissionEmployee

Fig.3| CommissionEmployeeclassderivedfromEmployee.

15. Whatisoutputbythefollowingcodesegment?Assumethatthecodeappearsinthemainmethodofanap- plication.
1 SalariedEmployeeemployee1 =
2 newSalariedEmployee(“June”,”Bug”,”123-45-6789″,1000.00 );
3
4 CommissionEmployee employee2 =
5 newCommissionEmployee(“Archie”,”Tic”,”987-65-4321″,15000.00,0.10 );
6
7 System.out.printf(“Employee 1:n%snn”,employee1 );
8 System.out.printf(“Employee 2:n%snn”,employee2 );
Youranswer:
Employee 1:
salaried employee:June Bug
socialsecuritynumber:123-45-6789
weeklysalary:$1,000.00

Employee 2:
commission employee:ArchieTic
socialsecuritynumber:987-65-4321
gross sales:$15,000.00;commission rate:0.10
16. Whatisoutputbythefollowingcodesegment?Assumethatthecodeappearsinthemainmethodofanap- plication.
1 Employee firstEmployee=
2 newSalariedEmployee(“June”,”Bug”,”123-45-6789″,1000.00 );
3
4 Employee secondEmployee =
5 newCommissionEmployee(“Archie”,”Tic”,”987-65-4321″,15000.00,0.10 );
6
7 System.out.printf(“Employee 1:n%snn”,firstEmployee);
8 System.out.printf(“Employee 2:n%snn”,secondEmployee );
Youranswer:
Employee 1:
salaried employee:June Bug
socialsecuritynumber:123-45-6789
weeklysalary:$1,000.00

Employee 2:
commission employee:ArchieTic
socialsecuritynumber:987-65-4321
gross sales:$15,000.00;commission rate:0.10
17. Whatisoutputbythefollowingcodesegment?AssumethatthecodefollowsthestatementsinProgramming
OutputExercise28.
1 SalariedEmployeesalaried = (SalariedEmployee)firstEmployee;
2 System.out.printf(“salaried:n%sn”,salaried);

Youranswer:
salaried:
salaried employee:June Bug
socialsecuritynumber:123-45-6789
weeklysalary:$1,000.00
18. Whatisoutputbythefollowingcodesegment?AssumethatthecodefollowsthestatementsinProgramming
OutputExercise17.
1 CommissionEmployee commission = (CommissionEmployee )firstEmployee;
2 System.out.println(“commission:n%sn”,commission );
Youranswer:
Althoughthecastinline1is allowedatcompiletime,thisresultsinaClassCastException atrun- timebecauseaSalariedEmployeeisnotaCommissionEmployee.
Exceptioninthread”main”java.lang.ClassCastException: SalariedEmployee atTest.main(Test.java:17)

Prelab Activity:
Correct the Code

Determineifthereisanerrorineachofthefollowingprogramsegments.Ifthereisanerror,specifywhetherit isalogicerroror acompilationerror,circletheerrorintheprogramandwritethecorrectedcodeinthespace providedaftereach problem.Ifthecodedoesnotcontainan error,write”noerror.”[Note:Theremaybemore thanoneerrorineachprogramsegment.]
Forquestions19-33assumethefollowingdefinitionofabstractclassEmployee.
1 // Employee abstractsuperclass.
2
3 publicabstractclassEmployee
4 {
5 privateStringfirstName;
6 privateStringlastName;
7
8 // three-argumentconstructor
9 publicEmployee(Stringfirst,Stringlast)
10 {
11 firstName= first;
12 lastName= last;
13 }// endthree-argumentEmployee constructor
14
15 // returnfirstname
16 publicStringgetFirstName()
17 {
18 returnfirstName;
19 }// endmethodgetFirstName
20
21 // returnlastname
22 publicStringgetLastName()
23 {
24 returnlastName;
25 }// endmethodgetLastName
26
27 // returnStringrepresentationof Employee object
28 publicStringtoString()
29 {
30 returnString.format(“%s %s”,getFirstName(),getLastName());
31 }// endmethodtoString
32
33 // abstractmethodoverriddenby subclasses
34 publicabstractdouble earnings();// noimplementationhere
35 }// endabstractclassEmployee

19. ThefollowingconcreteclassshouldinheritfromabstractclassEmployee.ATipWorkerispaidbythehour plustheirtipsfortheweek.

1 // TipWorker.java
2 publicfinal classTipWorker extends Employee
3 {
4 privatedouble wage; // wageper hour
5 privatedouble hours;// hours workedforweek
6 privatedouble tips;// tipsforthe week
7
8 publicTipWorker(Stringfirst,Stringlast,
9 double wagePerHour,double hoursWorked,double tipsEarned)
10 {
11 super(first,last); // call superclassconstructor
12 setWage (wagePerHour );
13 setHours(hoursWorked );
14 setTips(tipsEarned);
15 }
16
17 // setthe wage
18 publicvoid setWage(double wagePerHour )
19 {
20 wage= (wagePerHour<0?0:wagePerHour );
21 }
22
23 // setthe hours worked
24 publicvoid setHours(double hoursWorked )
25 {
26 hours = (hoursWorked >= 0&&hoursWorked <168?hoursWorked :0);
27 }
28
29 // setthe tips
30 publicvoid setTips(double tipsEarned)
31 {
32 tips= (tipsEarned<0?0:tipsEarned);
33 }
34 }// endclassTipWorker
Youranswer:

ClassTipWorkerdidnotimplementabstractmethodearningsthatwasinheritedfromclass
Employee.Theclassmustimplementthismethodtobeaconcreteclass.
1 // TipWorker.java
2 publicfinal classTipWorker extends Employee
3 {
4 privatedouble wage; // wageper hour
5 privatedouble hours;// hours workedforweek
6 privatedouble tips;// tipsforthe week
7
8 publicTipWorker(Stringfirst,Stringlast,
9 double wagePerHour,double hoursWorked,double tipsEarned)
10 {
11 super(first,last); // call superclassconstructor
12 setWage (wagePerHour );
13 setHours(hoursWorked );
14 setTips(tipsEarned);
15 }

16
17 // setthe wage
18 publicvoid setWage(double wagePerHour )
19 {
20 wage= (wagePerHour<0?0:wagePerHour );
21 }
22
23 // setthe hours worked
24 publicvoid setHours(double hoursWorked )
25 {
26 hours = (hoursWorked >= 0&&hoursWorked <168?hoursWorked :0);
27 }
28
29 // setthe tips
30 publicvoid setTips(double tipsEarned)
31 {
32 tips= (tipsEarned<0?0:tipsEarned);
33 }
34
35 // get the TipWorker’spay
36 publicdouble earnings()
37 {
38 return(wage* hours )+ tips;
39 }
40 }// endclassTipWorker
20. ThefollowingcodeshoulddefinemethodtoStringofclassTipWorkerinCorrecttheCodeExercise31.
1 // returna stringrepresentationof a TipWorker
2 publicStringtoString()
3 {
4 returnString.format(
5 “Tipworker:%sn%s:$%,.2f;%s: %.2f;%s: $%,.2fn”,toString(),
6 “hourlywage”,wage,”hoursworked”,hours,”tips earned”,tips);
7 }
Youranswer:

ThecalltotoStringinline5shouldcallthesuperclass’stoString;otherwise,thiscausesinfinite recursion.
1 // returna stringrepresentationof a TipWorker
2 publicStringtoString()
3 {
4 returnString.format(
5 “Tipworker:%sn%s:$%,.2f;%s: %.2f;%s: $%,.2fn”,super.toString(),
6 “hourlywage”,wage,”hoursworked”,hours,”tips earned”,tips);
7 }
21. ThefollowingcodeshouldinputinformationaboutfiveTipWorkersfromtheuserandthenprintthatin- formationandalltheTipWorkers’calculatedearnings.
1 // Test2.java
2 import java.util.Scanner;
3
4 publicclassTest2
5 {
6 publicstatic void main(Stringargs[])
7 {
8 Employee employee[];
9 Scanner input= newScanner(System.in);
10
11 for(inti= 0;i<employee.length;i++)
12 {
13 System.out.print(“Inputfirst name:”);
14 String firstName= input.nextLine();
15
16 System.out.print(“Inputlastname:”);
17 StringlastName = input.nextLine();
18
19 System.out.print(“Inputhours worked: “);
20 double hours = input.nextDouble();
21
22 System.out.print(“Inputtipsearned:”);
23 double tips= input.nextDouble();
24
25 employee[i]= newEmployee( firstName,lastName,2.63,hours,tips);
26
27 System.out.printf(“%s %searned $%.2fn”,employee[i].getFirstName(),
28 employee[ i].getLastName(),employee[ i].earnings());
29
30 input.nextLine();// clearany remainingcharactersinthe inputstream
31 }// endfor
32 }// endmain
33 }// endclassTest2
Youranswer:
1 // Test2.java
2 import java.util.Scanner;
3
4 publicclassTest2
5 {
6 publicstatic void main(Stringargs[])
7 {
8 Employee employee[]= newEmployee[ 5];
9 Scanner input= newScanner(System.in);
10
11 for(inti= 0;i<employee.length;i++)
12 {
13 System.out.print(“nInputfirstname:”);
14 String firstName= input.nextLine();
15
16 System.out.print(“Inputlastname:”);
17 StringlastName = input.nextLine();
18
19 System.out.print(“Inputhours worked: “);
20 double hours = input.nextDouble();
21
22 System.out.print(“Inputtipsearned:”);
23 double tips= input.nextDouble();
24
25 employee[i]= newTipWorker(firstName,lastName,2.63,hours,tips );
26
27 System.out.printf(“%s %searned $%.2fn”,employee[i].getFirstName(),
28 employee[ i].getLastName(),employee[ i].earnings());
29
30 input.nextLine();// clearany remainingcharactersinthe inputstream
31 }// endfor
32 }// endmain
33 }// endclassTest2

Lab Exercises:
Lab Exercise 1 – Payroll System Modification
Thisproblemisintendedtobesolvedinaclosed-labsessionwithateachingassistant orinstructorpresent.The problemisdividedintosixparts:
1. LabObjectives
2. DescriptionoftheProblem
3. SampleOutput
4. ProgramTemplate(Fig.L4-Fig.5)
5. Problem-SolvingTips
6. Follow-UpQuestionandActivity
TheprogramtemplaterepresentsacompleteworkingJavaprogram,withoneormorekeylinesofcodereplaced withcomments.Readtheproblemdescriptionandexaminethesampleoutput;thenstudythetemplatecode. Usingtheproblem-solving tipsasaguide,replacethecommentswithJavacode.Compileandexecutethe program.Compareyouroutputwiththesampleoutputprovided.Thenanswerthefollow-upquestions.The sourcecodeforthetemplate isavailableatwww.pearsonhighered.com/deitel.

LabObjectives
ThislabwasdesignedtoreinforceprogrammingconceptsfromChapter10ofJava HowtoProgram:8/e.Inthis lab,youwillpractice:
* Creatinganewclassandaddingit toanexistingclasshierarchy.
* Usingtheupdatedclasshierarchyinapolymorphicapplication.

Thefollow-upquestionandactivityalsowillgiveyoupractice:
* Understandingpolymorphism.

DescriptionoftheProblem
(PayrollSystemModification) Modifythepayrollsystemof Figs.4-9toincludeanadditionalEmployee subclassPieceWorkerthatrepresentsanemployeewhosepayisbasedonthenumber ofpiecesofmerchandise produced.ClassPieceWorkershouldcontainprivateinstancevariableswage(tostoretheemployee’swageper piece)andpieces(tostorethenumberofpiecesproduced).Provideaconcrete implementationofmethodearningsinclass PieceWorkerthatcalculatestheemployee’searningsbymultiplyingthenumberofpiecesproduced bythewageperpiece.CreateanarrayofEmployeevariablestostorereferencestoobjectsofeachconcreteclass inthenewEmployeehierarchy.ForeachEmployee,displayitsstringrepresentationandearnings.

SampleOutput
Employees processedpolymorphically:

salaried employee:John Smith
socialsecuritynumber:111-11-1111
weeklysalary:$800.00
earned $800.00

hourlyemployee: Karen Price
socialsecuritynumber:222-22-2222
hourlywage:$16.75;hours worked:40.00
earned $670.00

commission employee:Sue Jones socialsecuritynumber:333-33-3333
gross sales:$10,000.00;commission rate:0.06
earned $600.00

base-salariedcommission employee: BobLewis socialsecuritynumber:444-44-4444
gross sales: $5,000.00;commissionrate:0.04;base salary:$300.00 earned $500.00

pieceworker:Rick Bridges
socialsecuritynumber:555-55-5555
wageper piece:$2.25;pieces produced:400
earned $900.00
ProgramTemplate

1 // Lab Exercise1:PieceWorker.java
2 // PieceWorkerclass extends Employee.
3
4 publicclass PieceWorkerextends Employee
5 {
6
7
8
9 // five-argumentconstructor
10 publicPieceWorker(Stringfirst,Stringlast, Stringssn,
11 double wagePerPiece,int piecesProduced)
12 {
13
14 }// endfive-argumentPieceWorkerconstructor
15
16 // setwage
17
18
19 // returnwage
20
21
22 // set piecesproduced
23
24

Fig.4|PieceWorker.java.(Part1of2.)

25 // returnpiecesproduced
26
27
28 // calculate earnings;overrideabstractmethodearningsinEmployee
29 publicdouble earnings()
30 {
31
32 }// endmethodearnings
33
34 // returnStringrepresentationof PieceWorkerobject
35 publicStringtoString()
36 {
37
38 }// endmethodtoString
39 }// endclassPieceWorker

Fig.4|PieceWorker.java.(Part2of2.)

1 // Lab Exercise1:PayrollSystemTest.java
2 // Employee hierarchytestprogram.
3
4 publicclass PayrollSystemTest
5 {
6 publicstatic void main(Stringargs[])
7 {
8 // createfive-elementEmployee array
9 Employee employees[]= newEmployee[5];
10
11 // initialize arraywith 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
21
22 System.out.println(“Employeesprocessedpolymorphically:n” );
23
24 // generically processeach element inarrayemployees
25 for(Employee currentEmployee:employees )
26 {
27 System.out.println(currentEmployee);// invokestoString
28 System.out.printf(
29 “earned$%,.2fnn”,currentEmployee.earnings());
30 }// endfor
31 }// endmain
32 }// endclassPayrollSystemTest

Fig.5|PayrollSystemTest.java

Solution
1 // Lab Exercise1:PieceWorker
2 // PieceWorkerclass extends Employee.
3
4 publicclass PieceWorkerextends Employee
5 {
6 privatedouble wage; // wageper piece
7 privateintpieces;// piecesof merchandise produced inweek
8
9 // five-argumentconstructor
10 publicPieceWorker(Stringfirst,Stringlast, Stringssn,
11 double wagePerPiece,int piecesProduced)
12 {
13 super(first,last,ssn );
14 setWage(wagePerPiece);// validateandstorewageperpiece
15 setPieces(piecesProduced);// validateandstorepiecesproduced
16 }// endfive-argumentPieceWorkerconstructor
17
18 // setwage
19 publicvoid setWage(double wagePerPiece)
20 {
21 wage= (wagePerPiece<0.0 )? 0.0 :wagePerPiece;
22 }// endmethodsetWage
23
24 // returnwage
25 publicdouble getWage()
26 {
27 returnwage;
28 }// endmethodgetWage
29
30 // set piecesproduced
31 publicvoid setPieces(intpiecesProduced)
32 {
33 pieces= (piecesProduced<0)? 0:piecesProduced;
34 }// endmethodsetPieces
35
36 // returnpiecesproduced
37 publicintgetPieces()
38 {
39 returnpieces;
40 }// endmethodgetPieces
41
42 // calculate earnings;overrideabstractmethodearningsinEmployee
43 publicdouble earnings()
44 {
45 returngetPieces() * getWage();
46 }// endmethodearnings
47
48 // returnStringrepresentationof PieceWorkerobject
49 publicStringtoString()
50 {
51 returnString.format(“%s:%sn%s: $%,.2f;%s:%d”,
52 “pieceworker”,super.toString(),
53 “wage per piece”,getWage(),”piecesproduced”,getPieces());
54 }// endmethodtoString
55 }// endclassPieceWorker

1 // Lab Exercise1:PayrollSystemTest.java
2 // Employee hierarchytestprogram.
3
4 publicclass PayrollSystemTest
5 {
6 publicstatic void main(Stringargs[])
7 {
8 // createfive-elementEmployee array
9 Employee employees[]= newEmployee[5];
10
11 // initialize arraywith 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(“Employeesprocessedpolymorphically:n” );
24
25 // generically processeach element inarrayemployees
26 for(Employee currentEmployee:employees )
27 {
28 System.out.println(currentEmployee);// invokestoString
29 System.out.printf(
30 “earned$%,.2fnn”,currentEmployee.earnings());
31 }// endfor
32 }// endmain
33 }// endclassPayrollSystemTest

Problem-SolvingTips
1. ThePieceWorkerconstructorshouldcallthesuperclassEmployeeconstructorto initializetheemploy- ee’sname.
2. Thenumberofpiecesproducedshouldbegreaterthan orequalto 0.Place thislogicinthesetmethod forthepiecesvariable.
3. Thewageshouldbegreaterthanorequalto0.Placethislogicinthesetmethodforthewagevariable.
4. Themainmethodmustexplicitlycreatea newPieceWorkerobjectandassignittoanelementoftheemployeesarray.
5. Ifyouhaveanyquestionsasyouproceed,askyourlabinstructorforassistance.

Follow-UpQuestionandActivity
1. Explainthelineofcodein yourPayrollSystemTest’smainmethodthatcallsmethodearnings.Why canthatlineinvokemethodearningsoneveryelementoftheemployeesarray?
Thislineofcodeusespolymorphism toensurethateachEmployee’searningsiscalculatedcorrectly.Every elementofarrayemployeesreferstoanobjectthatisanEmployee.SinceclassEmployeedeclaresanabstract earningsmethod,everyconcretesubclassofEmployeemustimplementtheearningsmethod.Also,since objectscanbecreatedonlyfromconcreteclasses,itisguaranteedthattheobjecttowhichcurrentEmployee refersduringaniterationoftheforstatementwillhaveanearningsmethod.
Lab Exercises:
LabExercise2-AccountsPayableSystemModification

Thisproblemisintendedtobesolvedinaclosed-labsessionwithateachingassistant orinstructorpresent.The problemisdividedintosixparts:
1. LabObjectives
2. DescriptionoftheProblem
3. SampleOutput
4. ProgramTemplate(Fig.L10.6-Fig.L10.9)
5. Problem-SolvingTips
6. Follow-UpQuestionandActivity
TheprogramtemplaterepresentsacompleteworkingJavaprogram,withoneormorekeylinesofcodereplaced withcomments.Readtheproblemdescriptionandexaminethesampleoutput;thenstudythetemplatecode. Usingtheproblem-solving tipsasaguide,replacethecommentswithJavacode.Compileandexecutethe program.Compareyouroutputwiththesampleoutputprovided.Thenanswerthefollow-upquestion.The sourcecodeforthetemplate isavailableatwww.pearsonhighered.com/deitel.

LabObjectives
ThislabwasdesignedtoreinforceprogrammingconceptsfromChapter10ofJava HowtoProgram:8/e.Inthis labyouwillpractice:
* Provide additionalpolymorphicprocessingcapabilitiestoaninheritancehierarchybyimplementingan interface.
* Usingtheinstanceofoperatortodeterminewhether avariablerefersto anobjectthathasanis-arelationshipwithaparticularclass.
Thefollow-upquestionandactivitywillalsogiveyoupractice:
* Comparinginterfacesandabstractclasses.

DescriptionoftheProblem
(Accounts PayableSystemModification) In thisexercise,wemodifythe accountspayableapplicationofFigs.11-15toincludethecompletefunctionalityofthepayrollapplication.Theapplicationshouldstill processtwoInvoiceobjects, butnowshouldprocessoneobjectofeachofthefourEmployee subclasses(Figs.5-8).IftheobjectcurrentlybeingprocessedisaBasePlusCommissionEmployee,theapplication shouldincreasetheBasePlusCommissionEmployee’sbasesalaryby10%.Finally,theapplicationshouldoutput thepaymentamount foreachobject.Completethefollowingstepstocreatethenewapplication:
a) ModifyclassesHourlyEmployeeandCommissionEmployeetoplacetheminthePayablehierarchyassub- classesoftheversionofEmployeethatimplementsPayable(Fig.13).[Hint:Changethenameofmethod earningstogetPaymentAmountineachsubclasssothattheclasssatisfiesitsinheritedcontractwithinterface Payable.]
b) ModifyclassBasePlusCommissionEmployeesuchthatitextendstheversionofclassCommissionEmployeecreatedinParta.
c) ModifyPayableInterfaceTesttopolymorphically processtwoInvoices,oneSalariedEmployee,one HourlyEmployee,one CommissionEmployeeandoneBasePlusCommissionEmployee.Firstoutputastring representationofeachPayableobject.Next,ifanobjectisaBasePlusCommissionEmployee,increaseitsbase salaryby10%. Finally,outputthepayment amountforeachPayableobject.

SampleOutput
InvoicesandEmployees processedpolymorphically:

invoice:
partnumber:01234(seat)
quantity:2
priceper item:$375.00
paymentdue:$750.00

invoice:
partnumber:56789(tire)
quantity:4
priceper item:$79.95
paymentdue:$319.80

salaried employee:John Smith
socialsecuritynumber:111-11-1111
weeklysalary:$800.00
paymentdue:$800.00

hourlyemployee: Karen Price
socialsecuritynumber:222-22-2222
hourlywage:$16.75;hours worked:40.00
paymentdue:$670.00

commission employee:Sue Jones socialsecuritynumber:333-33-3333
gross sales:$10,000.00;commission rate:0.06
paymentdue:$600.00

base-salariedcommission employee: BobLewis socialsecuritynumber:444-44-4444
gross sales: $5,000.00;commissionrate:0.04;base salary:$300.00
newbase salarywith 10%increaseis:$330.00
paymentdue:$530.00
ProgramTemplate

1 // Lab Exercise2:HourlyEmployee.java
2 // HourlyEmployeeclass extends Employee,which implements Payable.
3
4 publicclassHourlyEmployeeextends Employee
5 {
6 privatedouble wage; // wageper hour
7 privatedouble hours;// hours workedforweek
8

Fig.6|HourlyEmployee.java.(Part1 of2.
9 // five-argumentconstructor
10 publicHourlyEmployee(String first,Stringlast,Stringssn,
11 double hourlyWage,double hoursWorked )
12 {
13 super(first,last,ssn );
14 setWage(hourlyWage );// validateandstorehourlywage
15 setHours(hoursWorked );// validateandstorehours worked
16 }// endfive-argumentHourlyEmployeeconstructor
17
18 // setwage
19 publicvoid setWage(double hourlyWage )
20 {
21 wage= (hourlyWage <0.0 )? 0.0 :hourlyWage;
22 }// endmethodsetWage
23
24 // returnwage
25 publicdouble getWage()
26 {
27 returnwage;
28 }// endmethodgetWage
29
30 // sethours worked
31 publicvoid setHours(double hoursWorked )
32 {
33 hours = ((hoursWorked >= 0.0 )&&(hoursWorked <= 168.0 ))?
34 hoursWorked :0.0;
35 }// endmethodsetHours
36
37 // returnhoursworked
38 publicdouble getHours()
39 {
40 returnhours;
41 }// endmethodgetHours
42
43 // calculate earnings;implement interface Payablemethodnot
44 // implementedby superclassEmployee
45
46 {
47 if(getHours()<= 40)// noovertime
48 return getWage()* getHours();
49 else
50 return40* getWage()+ (getHours()-40)* getWage()* 1.5;
51 }// endmethodgetPaymentAmount
52
53 // returnStringrepresentationof HourlyEmployeeobject
54 publicStringtoString()
55 {
56 returnString.format(“hourlyemployee:%sn%s:$%,.2f;%s: %,.2f”,
57 super.toString(),”hourlywage”,getWage(),
58 “hoursworked”,getHours());
59 }// endmethodtoString
60 }// endclassHourlyEmployee

Fig.6|HourlyEmployee.java.(Part2 of2.)

1 // Lab Exercise2:CommissionEmployee.java
2 // CommissionEmployeeclassextends Employee,which implementsPayable.
3
4 publicclassCommissionEmployeeextends Employee
5 {
6 privatedouble grossSales;// gross weeklysales
7 privatedouble commissionRate;// commission percentage
8
9 // five-argumentconstructor
10 publicCommissionEmployee( Stringfirst,Stringlast, Stringssn,
11 double sales,double rate)
12 {
13 super(first,last,ssn );
14 setGrossSales(sales);
15 setCommissionRate(rate );
16 }// endfive-argumentCommissionEmployee constructor
17
18 // setcommission rate
19 publicvoid setCommissionRate(double rate)
20 {
21 commissionRate = (rate>0.0&&rate<1.0 )?rate:0.0;
22 }// endmethodsetCommissionRate
23
24 // returncommission rate
25 publicdouble getCommissionRate()
26 {
27 returncommissionRate;
28 }// endmethodgetCommissionRate
29
30 // setgross salesamount
31 publicvoid setGrossSales(double sales)
32 {
33 grossSales= (sales<0.0 )?0.0 :sales;
34 }// endmethodsetGrossSales
35
36 // returngross salesamount
37 publicdouble getGrossSales()
38 {
39 returngrossSales;
40 }// endmethodgetGrossSales
41
42 // calculate earnings;implement interface Payablemethodnot
43 // implementedby superclassEmployee
44
45 {
46 returngetCommissionRate()* getGrossSales();
47 }// endmethodgetPaymentAmount
48
49 // returnStringrepresentationof CommissionEmployeeobject
50 publicStringtoString()
51 {
52 returnString.format(“%s:%sn%s: $%,.2f;%s:%.2f”,
53 “commission employee”,super.toString(),
54 “grosssales”,getGrossSales(),
55 “commission rate”,getCommissionRate());
56 }// endmethodtoString
57 }// endclassCommissionEmployee

Fig.7|CommissionEmployee.java.

1 // Lab Exercise2:BasePlusCommissionEmployee.java
2 // BasePlusCommissionEmployeeclassextends CommissionEmployee.
3
4 publicclassBasePlusCommissionEmployeeextends CommissionEmployee
5 {
6 privatedouble baseSalary;// base salaryper week
7
8 // six-argumentconstructor
9 publicBasePlusCommissionEmployee( Stringfirst,Stringlast,
10 Stringssn,double sales,double rate,double salary)
11 {
12 super(first,last,ssn,sales,rate);
13 setBaseSalary(salary);// validateandstorebase salary
14 }// endsix-argument BasePlusCommissionEmployeeconstructor
15
16 // setbase salary
17 publicvoid setBaseSalary(double salary)
18 {
19 baseSalary= (salary<0.0 )? 0.0 :salary;// non-negative
20 }// endmethodsetBaseSalary
21
22 // returnbase salary
23 publicdouble getBaseSalary()
24 {
25 returnbaseSalary;
26 }// endmethodgetBaseSalary
27
28 // calculate earnings;overrideCommissionEmployee implementation of
29 // interfacePayablemethod
30

31 {
32

33 }// endmethodgetPaymentAmount
34
35 // returnStringrepresentationof BasePlusCommissionEmployeeobject
36 publicStringtoString()
37 {
38 returnString.format(“%s %s;%s: $%,.2f”,
39 “base-salaried”,super.toString(),
40 “base salary”,getBaseSalary());
41 }// endmethodtoString
42 }// endclassBasePlusCommissionEmployee

Fig.8|BasePlusCommissionEmployee.java.

1 // Lab Exercise2:PayableInterfaceTest.java
2 // Testsinterface Payable.
3
4 publicclassPayableInterfaceTest
5 {
6 publicstatic void main(Stringargs[])
7 {
8 // create six-elementPayablearray
9 PayablepayableObjects[] = newPayable[6];
10

Fig.9|PayableInterfaceTest.java.(Part1of2.)

11 // populatearray withobjectsthatimplement Payable
12 payableObjects[0]= newInvoice(“01234″,”seat”,2,375.00 );
13 payableObjects[1]= newInvoice(“56789″,”tire”,4,79.95 );
14 payableObjects[2]=
15 newSalariedEmployee(“John”,”Smith”,”111-11-1111″,800.00 );
16 payableObjects[3]=
17
18 payableObjects[4]=
19
20 payableObjects[5]=
21
22
23 System.out.println(
24 “InvoicesandEmployeesprocessedpolymorphically:n” );
25
26 // generically processeach element inarraypayableObjects
27 for(PayablecurrentPayable :payableObjects)
28 {
29 // output currentPayableandits appropriatepaymentamount
30 System.out.printf(“%s n”,currentPayable.toString());
31
32

34 {
35
36

37 }// endif
38
39 System.out.printf(“%s:$%,.2fnn”,
40 “payment due”,currentPayable.getPaymentAmount());
41 }// endfor
42 }// endmain
43 }// endclassPayableInterfaceTest

Fig.9|PayableInterfaceTest.java.(Part2of2.)
Solution
1 // Lab Exercise2:HourlyEmployee.java
2 // HourlyEmployeeclass extends Employee,which implements Payable.
3
4 publicclassHourlyEmployeeextends Employee
5 {
6 privatedouble wage; // wageper hour
7 privatedouble hours;// hours workedforweek
8
9 // five-argumentconstructor
10 publicHourlyEmployee(String first,Stringlast,Stringssn,
11 double hourlyWage,double hoursWorked )
12 {
13 super(first,last,ssn );
14 setWage(hourlyWage );// validateandstorehourlywage
15 setHours(hoursWorked );// validateandstorehours worked
16 }// endfive-argumentHourlyEmployeeconstructor
17

18 // setwage
19 publicvoid setWage(double hourlyWage )
20 {
21 wage= (hourlyWage <0.0 )? 0.0 :hourlyWage;
22 }// endmethodsetWage
23
24 // returnwage
25 publicdouble getWage()
26 {
27 returnwage;
28 }// endmethodgetWage
29
30 // sethours worked
31 publicvoid setHours(double hoursWorked )
32 {
33 hours = ((hoursWorked >= 0.0 )&&(hoursWorked <= 168.0 ))?
34 hoursWorked :0.0;
35 }// endmethodsetHours
36
37 // returnhoursworked
38 publicdouble getHours()
39 {
40 returnhours;
41 }// endmethodgetHours
42
43 // calculate earnings;implement interface Payablemethodnot
44 // implementedby superclassEmployee
45 publicdouble getPaymentAmount()
46 {
47 if(getHours()<= 40)// noovertime
48 return getWage()* getHours();
49 else
50 return40* getWage()+ (getHours()-40)* getWage()* 1.5;
51 }// endmethodgetPaymentAmount
52
53 // returnStringrepresentationof HourlyEmployeeobject
54 publicStringtoString()
55 {
56 returnString.format(“hourlyemployee:%sn%s:$%,.2f;%s: %,.2f”,
57 super.toString(),”hourlywage”,getWage(),
58 “hoursworked”,getHours());
59 }// endmethodtoString
60 }// endclassHourlyEmployee

1 // Lab Exercise2:CommissionEmployee.java
2 // CommissionEmployeeclassextends Employee,which implementsPayable.
3
4 publicclassCommissionEmployeeextends Employee
5 {
6 privatedouble grossSales;// gross weeklysales
7 privatedouble commissionRate;// commission percentage
8
9 // five-argumentconstructor
10 publicCommissionEmployee( Stringfirst,Stringlast, Stringssn,
11 double sales,double rate)
12 {
13 super(first,last,ssn );
14 setGrossSales(sales);
15 setCommissionRate(rate );
16 }// endfive-argumentCommissionEmployee constructor
17
18 // setcommission rate
19 publicvoid setCommissionRate(double rate)
20 {
21 commissionRate = (rate>0.0&&rate<1.0 )?rate:0.0;
22 }// endmethodsetCommissionRate
23
24 // returncommission rate
25 publicdouble getCommissionRate()
26 {
27 returncommissionRate;
28 }// endmethodgetCommissionRate
29
30 // setgross salesamount
31 publicvoid setGrossSales(double sales)
32 {
33 grossSales= (sales<0.0 )?0.0 :sales;
34 }// endmethodsetGrossSales
35
36 // returngross salesamount
37 publicdouble getGrossSales()
38 {
39 returngrossSales;
40 }// endmethodgetGrossSales
41
42 // calculate earnings;implement interface Payablemethodnot
43 // implementedby superclassEmployee
44 publicdouble getPaymentAmount()
45 {
46 returngetCommissionRate()* getGrossSales();
47 }// endmethodgetPaymentAmount
48
49 // returnStringrepresentationof CommissionEmployeeobject
50 publicStringtoString()
51 {
52 returnString.format(“%s:%sn%s: $%,.2f;%s:%.2f”,
53 “commission employee”,super.toString(),
54 “grosssales”,getGrossSales(),
55 “commission rate”,getCommissionRate());
56 }// endmethodtoString
57 }// endclassCommissionEmployee
1 // Lab Exercise2:BasePlusCommissionEmployee.java
2 // BasePlusCommissionEmployeeclassextends CommissionEmployee.
3
4 publicclassBasePlusCommissionEmployeeextends CommissionEmployee
5 {
6 privatedouble baseSalary;// base salaryper week
7
8 // six-argumentconstructor
9 publicBasePlusCommissionEmployee( Stringfirst,Stringlast,
10 Stringssn,double sales,double rate,double salary)
11 {
12 super(first,last,ssn,sales,rate);
13 setBaseSalary(salary);// validateandstorebase salary
14 }// endsix-argument BasePlusCommissionEmployeeconstructor
15
16 // setbase salary
17 publicvoid setBaseSalary(double salary)
18 {
19 baseSalary= (salary<0.0 )? 0.0 :salary;// non-negative
20 }// endmethodsetBaseSalary
21
22 // returnbase salary
23 publicdouble getBaseSalary()
24 {
25 returnbaseSalary;
26 }// endmethodgetBaseSalary
27
28 // calculate earnings;overrideCommissionEmployee implementation of
29 // interfacePayablemethod
30 publicdouble getPaymentAmount()
31 {
32 returngetBaseSalary()+ super.getPaymentAmount();
33 }// endmethodgetPaymentAmount
34
35 // returnStringrepresentationof BasePlusCommissionEmployeeobject
36 publicStringtoString()
37 {
38 returnString.format(“%s %s;%s: $%,.2f”,
39 “base-salaried”,super.toString(),
40 “base salary”,getBaseSalary());
41 }// endmethodtoString
42 }// endclassBasePlusCommissionEmployee

1 // Lab Exercise2:PayableInterfaceTest.java
2 // Testsinterface Payable.
3
4 publicclassPayableInterfaceTest
5 {
6 publicstatic void main(Stringargs[])
7 {
8 // create six-elementPayablearray
9 PayablepayableObjects[] = newPayable[6];
10
11 // populatearray withobjectsthatimplement Payable
12 payableObjects[0]= newInvoice(“01234″,”seat”,2,375.00 );
13 payableObjects[1]= newInvoice(“56789″,”tire”,4,79.95 );
14 payableObjects[2]=
15 newSalariedEmployee(“John”,”Smith”,”111-11-1111″,800.00 );
16 payableObjects[3]=
17 newHourlyEmployee(“Karen”,”Price”,”222-22-2222″,16.75,40);
18 payableObjects[4]=
19 newCommissionEmployee(
20 “Sue”,”Jones”,”333-33-3333″,10000,.06 );
21 payableObjects[5]=
22 newBasePlusCommissionEmployee(
23 “Bob”,”Lewis”,”444-44-4444″,5000,.04,300);
24
25 System.out.println(
26 “InvoicesandEmployeesprocessedpolymorphically:n” );
27
28 // generically processeach element inarraypayableObjects
29 for(PayablecurrentPayable :payableObjects)
30 {
31 // output currentPayableandits appropriatepaymentamount
32 System.out.printf(“%s n”,currentPayable.toString());
33
34 if(currentPayableinstanceofBasePlusCommissionEmployee)
35 {
36 // downcast Payablereferenceto
37 // BasePlusCommissionEmployeereference
38 BasePlusCommissionEmployee employee =
39 (BasePlusCommissionEmployee )currentPayable;
40
41 doubleoldBaseSalary= employee.getBaseSalary();
42 employee.setBaseSalary(1.10 * oldBaseSalary);
43 System.out.printf(
44 “newbase salarywith10%%increaseis: $%,.2fn”,
45 employee.getBaseSalary());
46 }// endif
47
48 System.out.printf(“%s:$%,.2fnn”,
49 “payment due”,currentPayable.getPaymentAmount());
50 }// endfor
51 }// endmain
52 }// endclassPayableInterfaceTest
Problem-SolvingTips
1. EveryclassthatimplementsinterfacePayablemustdeclareamethodcalledgetPaymentAmount.
2. ClassBasePlusCommissionEmployeemustuseitssuperclass’sgetPaymentAmountmethodalongwithits ownbasesalarytocalculateitstotalearnings.
3. UsetheinstanceofoperatorinPayableInterfaceTesttodeterminewhethereachobjectisaBase- PlusCommissionEmployeeobject.
4. Ifyouhaveanyquestionsasyouproceed,askyourlabinstructorforassistance.

Follow-UpQuestionandActivity
1. Discussthebenefitsanddisadvantagesofextendinganabstractclassvs.implementinganinterface.
Abenefitofanabstractclassisthatyoucandeclarethe instancevariablesandmethodsthatarerequired byallclassesinahierarchy.Subclassescanthenenhancetheexistinginstancevariablesandmethodsinherited fromtheabstractclassandoverrideexistingmethodsasnecessary. Thisreducestheamount ofcodethat must bewrittentocreateeachnewclassinthehierarchy.Thisbenefitofabstractclassesisadisadvantageofinter- faces,whicharenotallowedtoprovideanymethodimplementationsorinstancevariables.Thus,anyclassthat implementsaninterfacemustdefinealltheinstancevariablesandmethods necessarytoproperlysatisfythe requirementsoftheinterface.
Abenefitofinterfacesisthatanyclasscanimplementaninterfacesuchthatobjectsofthatclasscanthenbe processedinapolymorphicprogramthatusesvariablesoftheinterfacetype.This isparticularly usefulfor extendingexistingsystems.
Adisadvantageofabstractclasses(andclassesingeneral)isthataclasscanextendonlyoneotherclassata time.However,aclasscanimplementmultipleinterfaces.

Lab Exercises:
Lab Exercise 3 -Debugging

Theprogram inthissectiondoesnotcompile.Fixallthesyntaxerrorsso thattheprogramwillcompilesuccess- fully.Oncetheprogramcompiles,executetheprogram,andcomparethe outputwiththesampleoutput;then eliminateanylogicerrorsthatmayexist.Thesampleoutputdemonstrateswhattheprogram’soutputshouldbe oncetheprogram’scodeiscorrected.Thesourcecodeis availableatwww.pearsonhighered.com/deitel.

SampleOutput
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
BrokenCode
1 // Shape.java
2 // Definitionof interface Shape
3
4 publicinterface Shape
5 {
6 publicabstractStringgetName();// returnshape name
7 }// endinterface Shape
1 // Point.java
2 // Definitionof classPoint
3
4 publicclassPointimplements Shape
5 {
6 protectedint x,y; // coordinatesof thePoint
7
8 // no-argumentconstructor
9 publicPoint()
10 {
11 setPoint(0,0);
12 }
13
14 // constructor
15 publicPoint(intxCoordinate,int yCoordinate)
16 {
17 setPoint(xCoordinate,yCoordinate);
18 }
19
20 // Setxandy coordinatesof Point
21 publicvoid setPoint(intxCoordinate,int yCoordinate)
22 {
23 x= xCoordinate;
24 y = yCoordinate;
25 }
26
27 // getxcoordinate
28 publicintgetX()
29 {
30 returnx;
31 }
32
33 // gety coordinate
34 publicintgetY()
35 {
36 returny;
37 }
38
39 // convertpointintoStringrepresentation
40 publicStringtoString()
41 {
42 returnString.format(“[%d,%d]”,x,y );
43 }
44
45 // calculate area
46 publicdouble area()
47 {
48 return0.0;
49 }
50
51 // calculate volume
52 publicdouble volume()
53 {
54 return0.0;
55 }
56
57 // returnshape name
58 publicStringgetName()
59 {
60 return”Point”;
61 }
62 }// endclassPoint
1 // Circle.java
2 // Definitionof classCircle
3
4 publicclassCircleextends Point
5 {
6 protecteddouble radius;
7
8 // no-argumentconstructor
9 publicCircle()
10 {
11 // implicitcallto superclassconstructorhere
12 setRadius(0);
13 }
14
15 // constructor
16 publicCircle(double circleRadius,intxCoordinate,int yCoordinate)
17 {
18 super(xCoordinate,yCoordinate);// call superclassconstructor
19
20 setRadius(circleRadius );
21 }
22
23 // setradiusof Circle
24 publicvoid setRadius(double circleRadius)
25 {
26 radius= (circleRadius>= 0?circleRadius:0);
27 }
28
29 // getradius of Circle
30 publicdouble getRadius()
31 {
32 returnradius;
33 }
34
35 // calculatearea of Circle
36 publicdouble area()
37 {
38 returnMath.PI* radius* radius;
39 }
40
41 // convertCircle to a Stringrepresention
42 publicStringtoString()
43 {
44 returnString.format(“Center= %s; Radius = %f”,
45 super.toString(),radius);
46 }
47
48 // returnshape name
49 publicStringgetName()
50 {
51 return”Circle”;
52 }
53 }// endclassCircle

1 // Cylinder.java
2 // Definitionof classCylinder.
3
4 publicclassCylinderextends Circle
5 {
6 protecteddouble height;// heightof Cylinder
7
8 // no-argumentconstructor
9 publicCylinder()
10 {
11 // implicitcallto superclassconstructorhere
12 setHeight(0);
13 }
14
15 // constructor
16 publicCylinder(double cylinderHeight,double cylinderRadius,
17 intxCoordinate,intyCoordinate)
18 {
19 // call superclassconstructor
20 super(cylinderRadius,xCoordinate,yCoordinate);
21
22 setHeight(cylinderHeight);
23 }
24
25 // setheightof Cylinder
26 publicvoid setHeight(double cylinderHeight)
27 {
28 height= (cylinderHeight>= 0?cylinderHeight:0);
29 }
30
31 // getheightof Cylinder
32 publicdouble getHeight()
33 {
34 returnheight;
35 }
36
37 // calculatearea of Cylinder(i.e.,surfacearea)
38 publicdouble area()
39 {
40 return2* super.area()+ 2* Math.PI* radius* height;
41 }
42
43 // calculatevolume of Cylinder
44 publicdouble volume()
45 {
46 returnsuper.area()* height;
47 }
48
49 // convertCylinderto a Stringrepresentation
50 publicStringtoString()
51 {
52 returnString.format(“%s; Height = %f”,
53 super.toString(),height);
54 }
55
56 // returnshape name
57 publicStringgetName()
58 {
59 return”Cylinder”;
60 }
61 }// endclassCylinder
1 // Test.java
2 // Test Point,Circle,Cylinderhierarchywith interfaceShape.
3
4 publicclassTest
5 {
6 // testShape hierarchy
7 publicstatic void main(Stringargs[])
8 {
9 // create shapes
10 Pointpoint= newPoint(7,11);
11 Circlecircle= newCircle(3.5,22,8);
12 Cylindercylinder= newCylinder(10,3.3,10,10);
13
14 CylinderarrayOfShapes[]= newCylinder[3];// createShape array
15
16 // aimarrayOfShapes[0]atsubclassPointobject
17 arrayOfShapes[0]= (Cylinder)point;
18
19 // aimarrayOfShapes[1]atsubclassCircle object
20 arrayOfShapes[1]= (Cylinder)circle;
21
22 // aimarrayOfShapes[2]atsubclassCylinderobject
23 arrayOfShapes[2]= (Cylinder)cylinder;
24
25 // get nameandStringrepresentationof each shape
26 System.out.printf(“%s:%sn%s: %sn%s: %sn”,point.getName(),
27 point,circle.getName(),circle,cylinder.getName(),cylinder);
28
29 // get name,area andvolume of each shape inarrayOfShapes
30 for(Shape shape :arrayOfShapes)
31 {
32 System.out.printf(“nn%s:%snArea = %.2fnVolume = %.2fn”,
33 shape.getName(),shape, shape.area(), shape.volume());
34 }// endfor
35 }// endmain
36 }// endclassTest
Solution
1 // Shape.java
2 // Definitionof interface Shape
3
4 publicinterface Shape
5 {
6 publicabstractdouble area();// calculate area
7 publicabstractdouble volume();// calculatevolume
8 publicabstractStringgetName();// returnshape name
9 }// endinterface Shape
1 // Point.java
2 // Definitionof classPoint
3
4 publicclassPointimplements Shape
5 {
6 protectedint x,y; // coordinatesof thePoint
7
8 // no-argumentconstructor
9 publicPoint()
10 {
11 setPoint(0,0);
12 }
13
14 // constructor
15 publicPoint(intxCoordinate,int yCoordinate)
16 {
17 setPoint(xCoordinate,yCoordinate);
18 }
19
20 // Setxandy coordinatesof Point
21 publicvoid setPoint(intxCoordinate,int yCoordinate)
22 {
23 x= xCoordinate;
24 y = yCoordinate;
25 }
26
27 // getxcoordinate
28 publicintgetX()
29 {
30 returnx;
31 }
32
33 // gety coordinate
34 publicintgetY()
35 {
36 returny;
37 }
38
39 // convertpointintoStringrepresentation
40 publicStringtoString()
41 {
42 returnString.format(“[%d,%d]”,x,y );
43 }
44
45 // calculate area
46 publicdouble area()
47 {
48 return0.0;
49 }
50
51 // calculate volume
52 publicdouble volume()
53 {
54 return0.0;
55 }
56
57 // returnshape name
58 publicStringgetName()
59 {
60 return”Point”;
61 }
62 }// endclassPoint
1 // Circle.java
2 // Definitionof classCircle
3
4 publicclassCircleextends Point
5 {
6 protecteddouble radius;
7
8 // no-argumentconstructor
9 publicCircle()
10 {
11 // implicitcallto superclassconstructorhere
12 setRadius(0);
13 }
14
15 // constructor
16 publicCircle(double circleRadius,intxCoordinate,int yCoordinate)
17 {
18 super(xCoordinate,yCoordinate);// call superclassconstructor
19
20 setRadius(circleRadius );
21 }
22
23 // setradiusof Circle
24 publicvoid setRadius(double circleRadius)
25 {
26 radius= (circleRadius>= 0?circleRadius:0);
27 }
28
29 // getradius of Circle
30 publicdouble getRadius()
31 {
32 returnradius;
33 }
34
35 // calculatearea of Circle
36 publicdouble area()
37 {
38 returnMath.PI* radius* radius;
39 }
40
41 // convertCircle to a Stringrepresention
42 publicStringtoString()
43 {
44 returnString.format(“Center= %s; Radius = %f”,
45 super.toString(),radius);
46 }
47
48 // returnshape name
49 publicStringgetName()
50 {
51 return”Circle”;
52 }
53 }// endclassCircle
1 // Cylinder.java
2 // Definitionof classCylinder.
3
4 publicclassCylinderextends Circle
5 {
6 protecteddouble height;// heightof Cylinder
7
8 // no-argumentconstructor
9 publicCylinder()
10 {
11 // implicitcallto superclassconstructorhere
12 setHeight(0);
13 }
14
15 // constructor
16 publicCylinder(double cylinderHeight,double cylinderRadius,
17 intxCoordinate,intyCoordinate)
18 {
19 // call superclassconstructor
20 super(cylinderRadius,xCoordinate,yCoordinate);
21
22 setHeight(cylinderHeight);
23 }
24
25 // setheightof Cylinder
26 publicvoid setHeight(double cylinderHeight)
27 {
28 height= (cylinderHeight>= 0?cylinderHeight:0);
29 }
30
31 // getheightof Cylinder
32 publicdouble getHeight()
33 {
34 returnheight;
35 }
36
37 // calculatearea of Cylinder(i.e.,surfacearea)
38 publicdouble area()
39 {
40 return2* super.area()+ 2* Math.PI* radius* height;
41 }
42
43 // calculatevolume of Cylinder
44 publicdouble volume()
45 {
46 returnsuper.area()* height;
47 }
48
49 // convertCylinderto a Stringrepresentation
50 publicStringtoString()
51 {
52 returnString.format(“%s; Height = %f”,
53 super.toString(),height);
54 }
55
56 // returnshape name
57 publicStringgetName()
58 {
59 return”Cylinder”;
60 }
61 }// endclassCylinder

1 // Test.java
2 // Test Point,Circle,Cylinderhierarchywith interfaceShape.
3
4 publicclassTest
5 {
6 // testShape hierarchy
7 publicstatic void main(Stringargs[])
8 {
9 // create shapes
10 Pointpoint= newPoint(7,11);
11 Circlecircle= newCircle(3.5,22,8);
12 Cylindercylinder= newCylinder(10,3.3,10,10);
13
14 Shape arrayOfShapes[]= newShape[ 3];// createShape array
15
16 // aimarrayOfShapes[0]atsubclassPointobject
17 arrayOfShapes[0]= point;
18
19 // aimarrayOfShapes[1]atsubclassCircle object
20 arrayOfShapes[1]= circle;
21
22 // aimarrayOfShapes[2]atsubclassCylinderobject
23 arrayOfShapes[2]= cylinder;
24
25 // get nameandStringrepresentationof each shape
26 System.out.printf(“%s:%sn%s: %sn%s: %sn”,point.getName(),
27 point,circle.getName(),circle,cylinder.getName(),cylinder);
28
29 // get name,area andvolume of each shape inarrayOfShapes
30 for(Shape shape :arrayOfShapes)
31 {
32 System.out.printf(“nn%s:%snArea = %.2fnVolume = %.2fn”,
33 shape.getName(),shape, shape.area(), shape.volume());
34 }// endfor
35 }// endmain
36 }// endclassTest
ListofErrors
* Shape.java:TheShapeinterfacemustdeclarepublicabstractmethodsarea andvolume.
* Test.java,line14:ThearrayshouldbeoftypeShapesothatthearrayelementscanrefertoPoint,CircleandCylinderobjectsforpolymorphicprocessing.
* Test.java,line17:Oncethe arrayischangedtotypeShape,itisnotnecessarytocastpointtoadif- ferenttype-aPointobjectcanalwaysbeassignedtoaShapevariablebasedonthehierarchydefined in thisexercise.
* Test.java,line20:OncethearrayischangedtotypeShape,itisnotnecessarytocastcircletoadif- ferenttype-aCircleobjectcanalwaysbeassignedtoaShapevariablebasedonthehierarchydefined in thisexercise.
* Test.java,line23:Thecastoperationisunnecessary-aCylinderobjectcanalwaysbeassignedtoaShapevariablebasedon thehierarchydefinedinthisexercise.
Postlab Activities
Coding Exercises
Thesecodingexercisesreinforcethelessonslearnedinthelabandprovideadditionalprogrammingexperience outsidetheclassroomandlaboratoryenvironment.Theyserveasareview afteryouhavesuccessfullycompleted thePrelabActivitiesandLabExercises.

Foreachofthefollowingproblems,writeaprogramoraprogramsegmentthatperformsthespecifiedaction.
1. Writeanemptyclassdeclaration foranabstractclasscalledShape.

1 // Shape.java
2 // Shape classdeclaration.
3
4 publicabstractclassShape
5 {
6 }// endclassShape
2. IntheclassfromCodingExercise1,createaprotectedinstancevariableshapeNameoftypeString,andwrite anaccessormethodgetNameforobtainingitsvalue.

1 // Shape.java
2 // Shape classdeclaration.
3
4 publicabstractclassShape
5 {
6 protectedString shapeName;
7
8 publicStringgetName()
9 {
10 returnshapeName;
11 }
12 }// endclassShape
3. IntheclassofCodingExercise2,defineanabstractmethodgetAreathatreturnsadoublerepresentation ofaspecificshape’sarea.SubclassesofthisclassmustimplementgetAreatocalculateaspecificshape’s area.

1 // Shape.java
2 // Shape classdeclaration.
3
4 publicabstractclassShape
5 {
6 protectedString shapeName;
7
8 // abstract getAreamethod mustbeimplemented by concretesubclasses
9 publicabstractdouble getArea();
10
11 publicStringgetName()
12 {
13 returnshapeName;
14 }
15 }// endclassShape
4. Definea classSquare thatinheritsfromclassShapefromCodingExercise3; itshouldcontainaninstance variableside, whichrepresentsthelengthofasideofthesquare.Provideaconstructor thattakesoneargumentrepresentingthesideofthesquareandsetsthesidevariable. Ensurethatthesideisgreaterthanor equalto0.TheconstructorshouldsettheinheritedshapeNamevariabletothestring”Square”.
1 // Square.java
2 // Definitionof classSquare.
3
4 publicclassSquare extends Shape
5 {
6 privatedouble side;
7
8 // constructor
9 publicSquare(double s )
10 {
11 side= (s <0?0:s );
12 shapeName= “Square”;
13 }
14 }// endclassSquare
5. TheSquareclassfromCodingExercise4 shouldimplementthegetArea methodofitsabstractsuperclass;thisimplementationshouldcomputetheareaofthesquareandreturn theresult.
1 // Square.java
2 // Definitionof classSquare.
3
4 publicclassSquare extends Shape
5 {
6 privatedouble side;
7
8 // constructor
9 publicSquare(double s )
10 {
11 side= (s <0?0:s );
12 shapeName= “Square”;
13 }
14
15 // returnthe area of a Square
16 publicdouble getArea()
17 {
18 returnside* side;
19 }
20 }// endclassSquare

6. DefineaclassRectanglethatinheritsfromclassShapeofCodingExercise3.Thenewclassshouldcontain instancevariableslengthandwidth.Provideaconstructorthattakestwoargumentsrepresentingthelength andwidthoftherectangle,setsthetwovariablesandsetstheinheritedshapeName variabletothestring “Rectangle”.Ensurethat thelengthandwidtharebothgreaterthanorequalto 0.
1 // Rectangle.java
2 // Rectangleclass declaration.
3
4 publicclassRectangleextends Shape
5 {
6 privatedouble length,width;
7
8 // constructor
9 publicRectangle(doubles1, double s2 )
10 {
11 length= (s1 <0?0:s1 );
12 width= (s2 <0?0:s2 );
13 shapeName= “Rectangle”;
14 }
15 }// endclassRectangle
7. TheRectangleclassfromCodingExercise6shouldalsoimplementthegetAreamethodofitsabstractsuperclass;thisimplementationshould computetheareaoftherectangleandreturn theresult.
1 // Rectangle.java
2 // Rectangleclass declaration.
3
4 publicclassRectangleextends Shape
5 {
6 privatedouble length,width;
7
8 // constructor
9 publicRectangle(doubles1, double s2 )
10 {
11 length= (s1 <0?0:s1 );
12 width= (s2 <0?0:s2 );
13 shapeName= “Rectangle”;
14 }
15
16 // returnthe area of a Rectangle
17 publicdouble getArea()
18 {
19 returnlength* width;
20 }
21 }// endclassRectangle
8. WriteanapplicationthatteststheSquareandRectangleclassesfromCodingExercises5and7,respectively.
CreateanarrayoftypeShapethatholds aninstanceofSquareandaninstanceofRectangle.Theprogram shouldpolymorphicallycomputeanddisplaytheareasofbothobjects.Allow ausertoenterthe valuesfor thesideofthesquareandthelengthandwidthoftherectangle.
1 // TestArea.java
2 import java.util.Scanner;
3
4 publicclassTestArea
5 {
6 publicstatic void main(Stringargs[])
7 {
8 Scanner input= newScanner(System.in);
9
10 System.out.print(“Inputthe sideof the square:”);
11 double side= input.nextDouble();
12
13 System.out.print(“Inputthe lengthof the rectangle:”);
14 double length= input.nextDouble();
15
16 System.out.print(“Inputthe width ofthe rectangle:”);
17 double width = input.nextDouble();
18
19 Shape arrayOfShapes[]= newShape[ 2];
20 arrayOfShapes[0]= newSquare(side);
21 arrayOfShapes[1]= newRectangle(length,width);
22
23 for(Shape shape :arrayOfShapes)
24 System.out.printf(“The %shas anarea of %.2fn”,shape.getName(),
25 shape.getArea());
26 }// endmain
27 }// endclass TestArea

Inputthe sideof thesquare:10.5
Inputthe lengthof the rectangle:2.5
Inputthe width of the rectangle:3.5
TheSquare has anarea of 110.25
TheRectanglehas anarea of 8.75

PostlabActivities
ProgrammingChallenges
TheProgrammingChallengesaremoreinvolvedthanthe CodingExercisesand mayrequireasignificantamount oftimetocomplete.WriteaJavaprogramforeachoftheproblemsinthissection.Theanswerstotheseproblems areavailableat www.pearsonhighered.com/deitel.Pseudocode,hintsorsampleoutputsareprovidedforeach problemtoaidyouinyourprogramming.
9. (PayrollSystemModification)ModifythepayrollsystemofFigs.10.4-10.9toincludeprivateinstancevariablebirthDateinclassEmployee.UseclassDateofFig.8.7torepresentanemployee’sbirthday.Addget methodstoclassDateandreplacemethodtoDateStringwithmethodtoString.Assumethatpayrollisprocessedonceper month.Createanarrayof Employeevariablestostorereferencestothevariousemployee objects.Inaloop,calculatethepayrollforeachEmployee(polymorphically),andadda$100.00bonusto theperson’spayrollamount ifthecurrentmonthisthemonthinwhichtheEmployee’sbirthdayoccurs.

Hint:
• Youroutputshouldappearasfollows:
Dateobjectconstructorfordate 6/15/1944
Dateobjectconstructorfordate 12/29/1960
Dateobjectconstructorfordate 9/8/1954
Dateobjectconstructorfordate 3/2/1965
Employees processedindividually:

salaried employee:John Smith
socialsecuritynumber:111-11-1111
birthdate:6/15/1944
weeklysalary:$800.00
earned:$800.00

hourlyemployee: Karen Price
socialsecuritynumber:222-22-2222
birthdate:12/29/1960
hourlywage:$16.75;hours worked: 40.00
earned:$670.00

commission employee:Sue Jones socialsecuritynumber:333-33-3333 birthdate:9/8/1954
gross sales:$10,000.00;commission rate:0.06 earned:$600.00

base-salariedcommission employee:BobLewis socialsecuritynumber:444-44-4444
birthdate:3/2/1965
gross sales: $5,000.00;commission rate:0.04;base salary:$300.00
earned:$500.00

Enterthe currentmonth(1 -12): 3

(continuednextpage…)
Employees processedpolymorphically:

salaried employee:John Smith
socialsecuritynumber:111-11-1111
birthdate:6/15/1944
weeklysalary:$800.00
earned $800.00

hourlyemployee: Karen Price
socialsecuritynumber:222-22-2222
birthdate:12/29/1960
hourlywage:$16.75;hours worked:40.00
earned $670.00

commission employee:Sue Jones socialsecuritynumber:333-33-3333 birthdate:9/8/1954
gross sales:$10,000.00;commission rate:0.06
earned $600.00

base-salariedcommission employee: BobLewis socialsecuritynumber:444-44-4444
birthdate:3/2/1965
gross sales: $5,000.00;commissionrate:0.04;base salary:$300.00
newbase salarywith 10%increaseis:$330.00
earned $530.00 plus $100.00 birthdaybonus

Employee 0isa SalariedEmployee Employee 1isa HourlyEmployee Employee 2isa CommissionEmployee
Employee 3isa BasePlusCommissionEmployee
Solution
1 // ProgrammingChallenge1:Employee.java
2 // Employee abstractsuperclass.
3
4 publicabstractclassEmployee
5 {
6 privateStringfirstName;
7 privateStringlastName;
8 privateStringsocialSecurityNumber;
9 privateDate birthDate;
10
11 // six-argumentconstructor
12 publicEmployee(Stringfirst,Stringlast,Stringssn,
13 intmonth, intday, intyear)
14 {
15 firstName= first;
16 lastName= last;
17 socialSecurityNumber= ssn;
18 birthDate= newDate(month,day, year );
19 }// endsix-argumentEmployee constructor
20
21 // setfirst name
22 publicvoid setFirstName(Stringfirst)
23 {
24 firstName= first;

25 }// endmethodsetFirstName
26
27 // returnfirstname
28 publicStringgetFirstName()
29 {
30 returnfirstName;
31 }// endmethodgetFirstName
32
33 // setlastname
34 publicvoid setLastName(Stringlast)
35 {
36 lastName= last;
37 }// endmethodsetLastName
38
39 // returnlastname
40 publicStringgetLastName()
41 {
42 returnlastName;
43 }// endmethodgetLastName
44
45 // setsocialsecuritynumber
46 publicvoid setSocialSecurityNumber(String ssn )
47 {
48 socialSecurityNumber= ssn; // shouldvalidate
49 }// endmethodsetSocialSecurityNumber
50
51 // returnsocialsecuritynumber
52 publicStringgetSocialSecurityNumber()
53 {
54 returnsocialSecurityNumber;
55 }// endmethodgetSocialSecurityNumber
56
57 // setbirth date
58 publicvoid setBirthDate(intmonth, intday, intyear )
59 {
60 birthDate= newDate(month,day, year );
61 }// endmethodsetBirthDate
62
63 // returnbirth date
64 publicDate getBirthDate()
65 {
66 returnbirthDate;
67 }// endmethodgetBirthDate
68
69 // returnStringrepresentationof Employee object
70 publicStringtoString()
71 {
72 returnString.format(“%s %sn%s: %sn%s: %s”,
73 getFirstName(),getLastName(),
74 “socialsecuritynumber”,getSocialSecurityNumber(),
75 “birthdate”,getBirthDate());
76 }// endmethodtoString
77
78 // abstractmethodoverriddenby subclasses
79 publicabstractdouble earnings();
80 }// endabstractclassEmployee
1 // ProgrammingChallenge1:Date.java
2 // Date classdeclarationwith getmethodsadded.
3
4 publicclassDate
5 {
6 privateintmonth;// 1-12
7 privateintday; // 1-31based onmonth
8 privateintyear; // any year
9
10 // constructor:callcheckMonth to confirmpropervalueformonth;
11 // callcheckDay to confirmproper valuefor day
12 publicDate(inttheMonth,int theDay,int theYear)
13 {
14 month= checkMonth( theMonth );// validatemonth
15 year = theYear;// could validateyear
16 day = checkDay(theDay );// validate day
17
18 System.out.printf(
19 “Date objectconstructorfordate %sn”,toString() );
20 }// endDate constructor
21
22 // utilitymethod to confirmproper monthvalue
23 privateintcheckMonth(int testMonth)
24 {
25 if(testMonth>0&&testMonth<= 12)// validatemonth
26 returntestMonth;
27 else// monthisinvalid
28 {
29 System.out.printf(“Invalidmonth(%d)set to 1.n”,testMonth);
30 return1;// maintainobjectinconsistentstate
31 }// endelse
32 }// endmethodcheckMonth
33
34 // utilitymethod to confirmproper day valuebased onmonthandyear
35 private int checkDay(int testDay)
36 {
37 intdaysPerMonth[]=
38 {0,31,28,31,30,31,30,31,31,30,31,30,31};
39
40 // check ifday inrange formonth
41 if(testDay>0&&testDay<= daysPerMonth[month])
42 returntestDay;
43
44 // check forleap year
45 if(month== 2&&testDay== 29&&(year %400== 0||
46 (year%4== 0&&year%100!= 0)))
47 returntestDay;
48
49 System.out.printf(“Invalid day (%d)set to 1.n”,testDay);
50
51 return1; // maintainobjectinconsistentstate
52 }// endmethodcheckDay
53
54 // returnday
55 publicintgetDay()
56 {
57 returnday;
58 }// endmethodgetDay
59
60 // returnmonth
61 publicintgetMonth()
62 {
63 returnmonth;
64 }// endmethodgetMonth
65
66 // returnyear
67 publicintgetYear()
68 {
69 returnyear;
70 }// endmethodgetYear
71
72 // returna Stringof the form month/day/year
73 publicStringtoString()
74 {
75 returnString.format(“%d/%d/%d”,month,day, year );
76 }// endmethodtoString
77 }// endclassDate
1 // ProgrammingChallenge1:SalariedEmployee.java
2 // SalariedEmployeeclass derivedfrom Employee.
3
4 publicclass SalariedEmployeeextends Employee
5 {
6 privatedouble weeklySalary;
7
8 // seven-argument constructor
9 publicSalariedEmployee(Stringfirst,Stringlast,Stringssn,
10 intmonth, intday, intyear,double salary)
11 {
12 super(first, last,ssn,month,day, year );
13 setWeeklySalary(salary);
14 }// endseven-argumentSalariedEmployeeconstructor
15
16 // setsalary
17 publicvoid setWeeklySalary(double salary)
18 {
19 weeklySalary= salary<0.0 ?0.0 :salary;
20 }// endmethodsetWeeklySalary
21
22 // returnsalary
23 publicdouble getWeeklySalary()
24 {
25 returnweeklySalary;
26 }// endmethodgetWeeklySalary
27
28 // calculate earnings;overrideabstractmethodearningsinEmployee
29 publicdouble earnings()
30 {
31 returngetWeeklySalary();
32 }// endmethodearnings
33
34 // returnStringrepresentationof SalariedEmployeeobject
35 publicStringtoString()
36 {

37 returnString.format(“salariedemployee:%sn%s: $%,.2f”,
38 super.toString(),”weeklysalary”,getWeeklySalary());
39 }// endmethodtoString
40 }// endclassSalariedEmployee

1 // ProgrammingChallenge1:HourlyEmployee.java
2 // HourlyEmployeeclass derivedfromEmployee.
3
4 publicclassHourlyEmployeeextends Employee
5 {
6 privatedouble wage; // wageper hour
7 privatedouble hours;// hours workedforweek
8
9 // eight-argumentconstructor
10 publicHourlyEmployee(String first,Stringlast,Stringssn,
11 intmonth, intday, intyear,
12 double hourlyWage,double hoursWorked )
13 {
14 super(first, last,ssn,month,day, year );
15 setWage(hourlyWage );
16 setHours(hoursWorked );
17 }// endeight-argumentHourlyEmployeeconstructor
18
19 // setwage
20 publicvoid setWage(double hourlyWage )
21 {
22 wage= hourlyWage <0.0 ?0.0:hourlyWage;
23 }// endmethodsetWage
24
25 // returnwage
26 publicdouble getWage()
27 {
28 returnwage;
29 }// endmethodgetWage
30
31 // sethours worked
32 publicvoid setHours(double hoursWorked )
33 {
34 hours = ((hoursWorked >= 0.0 )&&(hoursWorked <= 168.0 ))?
35 hoursWorked :0.0;
36 }// endmethodsetHours
37
38 // returnhoursworked
39 publicdouble getHours()
40 {
41 returnhours;
42 }// endmethodgetHours
43
44 // calculate earnings;overrideabstractmethodearningsinEmployee
45 publicdouble earnings()
46 {
47 if(getHours()<= 40)// noovertime
48 return getWage()* getHours();
49 else
50 return40* getWage()+ (getHours()-40)* getWage()* 1.5;
51 }// endmethodearnings
52
53 // returnStringrepresentationof HourlyEmployeeobject
54 publicStringtoString()
55 {
56 returnString.format(“hourlyemployee:%sn%s:$%,.2f;%s: %,.2f”,
57 super.toString(),”hourlywage”,getWage(),
58 “hoursworked”,getHours());
59 }// endmethodtoString
60 }// endclassHourlyEmployee
1 // ProgrammingChallenge1:CommissionEmployee.java
2 // CommissionEmployeeclassderivedfrom Employee.
3
4 publicclassCommissionEmployeeextends Employee
5 {
6 privatedouble grossSales;// gross weeklysales
7 privatedouble commissionRate;// commission percentage
8
9 // eight-argumentconstructor
10 publicCommissionEmployee( Stringfirst,Stringlast, Stringssn,
11 intmonth, intday, intyear,double sales,double rate)
12 {
13 super(first, last,ssn,month,day, year );
14 setGrossSales(sales);
15 setCommissionRate(rate );
16 }// endeight-argumentCommissionEmployee constructor
17
18 // setcommission rate
19 publicvoid setCommissionRate(double rate)
20 {
21 commissionRate = (rate>0.0&&rate<1.0 )?rate:0.0;
22 }// endmethodsetCommissionRate
23
24 // returncommission rate
25 publicdouble getCommissionRate()
26 {
27 returncommissionRate;
28 }// endmethodgetCommissionRate
29
30 // setgross salesamount
31 publicvoid setGrossSales(double sales)
32 {
33 grossSales= sales<0.0 ?0.0 :sales;
34 }// endmethodsetGrossSales
35
36 // returngross salesamount
37 publicdouble getGrossSales()
38 {
39 returngrossSales;
40 }// endmethodgetGrossSales
41
42 // calculate earnings;overrideabstractmethodearningsinEmployee
43 publicdouble earnings()
44 {
45 returngetCommissionRate()* getGrossSales();
46 }// endmethodearnings
47
48 // returnStringrepresentationof CommissionEmployeeobject
49 publicStringtoString()
50 {
51 returnString.format(“%s:%sn%s: $%,.2f;%s:%.2f”,
52 “commission employee”,super.toString(),
53 “grosssales”,getGrossSales(),
54 “commission rate”,getCommissionRate());
55 }// endmethodtoString
56 }// endclassCommissionEmployee
1 // ProgrammingChallenge1:BasePlusCommissionEmployee.java
2 // BasePlusCommissionEmployeeclassderivedfrom CommissionEmployee.
3
4 publicclassBasePlusCommissionEmployeeextends CommissionEmployee
5 {
6 privatedouble baseSalary;// base salaryper week
7
8 // nine-argument constructor
9 publicBasePlusCommissionEmployee( Stringfirst,Stringlast,
10 Stringssn,intmonth,intday, intyear,
11 double sales,double rate,double salary)
12 {
13 super(first, last,ssn,month,day, year,sales,rate);
14 setBaseSalary(salary);
15 }// endnine-argument BasePlusCommissionEmployee constructor
16
17 // setbase salary
18 publicvoid setBaseSalary(double salary)
19 {
20 baseSalary= salary<0.0 ?0.0 :salary;// non-negative
21 }// endmethodsetBaseSalary
22
23 // returnbase salary
24 publicdouble getBaseSalary()
25 {
26 returnbaseSalary;
27 }// endmethodgetBaseSalary
28
29 // calculate earnings;overridemethodearningsinCommissionEmployee
30 publicdouble earnings()
31 {
32 returngetBaseSalary()+ super.earnings();
33 }// endmethodearnings
34
35 // returnStringrepresentationof BasePlusCommissionEmployeeobject
36 publicStringtoString()
37 {
38 returnString.format(“%s %s;%s: $%,.2f”,
39 “base-salaried”,super.toString(),
40 “base salary”,getBaseSalary());
41 }// endmethodtoString
42 }// endclassBasePlusCommissionEmployee
1 // ProgrammingChallenge1:PayrollSystemTest.java
2 // Employee hierarchytestprogram.
3 import java.util.Scanner;// programuses Scanner toobtainuser input
4
5 publicclass PayrollSystemTest
6 {
7 publicstatic void main(Stringargs[])
8 {
9 // createsubclassobjects
10 SalariedEmployeesalariedEmployee=
11 newSalariedEmployee(
12 “John”,”Smith”,”111-11-1111″,6,15,1944,800.00 );
13 HourlyEmployeehourlyEmployee=
14 newHourlyEmployee(
15 “Karen”,”Price”,”222-22-2222″,12,29,1960,16.75,40);
16 CommissionEmployee commissionEmployee =
17 newCommissionEmployee(
18 “Sue”,”Jones”,”333-33-3333″,9,8,1954,10000,.06);
19 BasePlusCommissionEmployee basePlusCommissionEmployee =
20 newBasePlusCommissionEmployee(
21 “Bob”,”Lewis”,”444-44-4444″,3,2,1965,5000,.04,300);
22
23 System.out.println(“Employeesprocessedindividually:n”);
24
25 System.out.printf( “%sn%s:$%,.2fnn”,
26 salariedEmployee,”earned”,salariedEmployee.earnings());
27 System.out.printf( “%sn%s:$%,.2fnn”,
28 hourlyEmployee,”earned”,hourlyEmployee.earnings());
29 System.out.printf( “%sn%s:$%,.2fnn”,
30 commissionEmployee, “earned”,commissionEmployee.earnings());
31 System.out.printf( “%sn%s:$%,.2fnn”,
32 basePlusCommissionEmployee,
33 “earned”,basePlusCommissionEmployee.earnings() );
34
35 // create four-elementEmployee array
36 Employee employees[]= newEmployee[4];
37
38 // initialize arraywith Employees
39 employees[0]= salariedEmployee;
40 employees[1]= hourlyEmployee;
41 employees[2]= commissionEmployee;
42 employees[3]= basePlusCommissionEmployee;
43
44 Scanner input= newScanner(System.in);// to get currentmonth
45 intcurrentMonth;
46
47 // get andvalidatecurrentmonth
48 do
49 {
50 System.out.print(“Enterthe currentmonth(1 -12):”);
51 currentMonth= input.nextInt();
52 System.out.println();
53 }while((currentMonth<1)||(currentMonth>12));
54
55 System.out.println(“Employeesprocessedpolymorphically:n” );
56

57 // generically processeach element inarrayemployees
58 for(Employee currentEmployee:employees )
59 {
60 System.out.println(currentEmployee);// invokestoString
61
62 // determinewhether elementisa BasePlusCommissionEmployee
63 if(currentEmployeeinstanceof BasePlusCommissionEmployee)
64 {
65 // downcast Employee referenceto
66 // BasePlusCommissionEmployeereference
67 BasePlusCommissionEmployee employee =
68 (BasePlusCommissionEmployee )currentEmployee;
69
70 doubleoldBaseSalary= employee.getBaseSalary();
71 employee.setBaseSalary(1.10 * oldBaseSalary);
72 System.out.printf(
73 “newbase salarywith10%%increaseis: $%,.2fn”,
74 employee.getBaseSalary());
75 }// endif
76
77 // ifmonthof employee’sbirthday, add$100to salary
78 if(currentMonth== currentEmployee.getBirthDate().getMonth())
79 System.out.printf(
80 “earned$%,.2f%snn”,currentEmployee.earnings(),
81 “plus$100.00 birthdaybonus”);
82 else
83 System.out.printf(
84 “earned$%,.2fnn”,currentEmployee.earnings());
85 }// endfor
86
87 // get type nameof each objectinemployees array
88 for(intj= 0;j <employees.length;j++)
89 System.out.printf(“Employee %disa %sn”,j,
90 employees[j ].getClass().getName());
91 }// endmain
92 }// endclassPayrollSystemTest
10. (ShapeHierarchy)ImplementtheShapehierarchyshowninFig.9.3ofJavaHowtoProgram.EachTwoDimensionalShapeshouldcontainmethodgetAreatocalculatetheareaofthetwo-dimensionalshape.Each ThreeDimensionalShapeshouldhavemethodsgetAreaandgetVolumetocalculate thesurfaceareaandvolume,respectively,ofthethree-dimensionalshape.CreateaprogramthatusesanarrayofShapereferences toobjectsofeachconcreteclassin thehierarchy.Theprogramshouldprintatextdescriptionoftheobject towhicheacharrayelementrefers.Also,intheloopthatprocessesalltheshapesinthearray,determine whethereachshapeisaTwoDimensionalShape oraThreeDimensionalShape.IfashapeisaTwoDimensionalShape, displayitsarea.IfashapeisaThreeDimensionalShape,displayitsareaandvolume.

Hint:
• Youroutputshouldappearasfollows:
Circle:[22,88] radius:4
Circle’sarea is50

Square:[71,96] side:10
Square’sarea is100

Sphere:[8,89] radius:2
Sphere’sarea is50
Sphere’svolume is33

Cube: [79,61] side:8
Cube’s area is384
Cube’s volumeis512
Solution
1 // ProgrammingChallenge2:Shape.java
2 // Definitionof classShape.
3
4 publicabstractclassShape
5 {
6 privateintx;// xcoordinate
7 privateinty;// y coordinate
8
9 // two-argumentconstructor
10 publicShape( intx,inty )
11 {
12 this.x= x;
13 this.y= y;
14 }// endtwo-argument Shape constructor
15
16 // setxcoordinate
17 publicvoid setX( intx)
18 {
19 this.x= x;
20 }// endmethodsetX
21
22 // sety coordinate
23 publicvoid setY(inty )
24 {
25 this.y= y;
26 }// endmethodsetY

27
28 // getxcoordinate
29 publicintgetX()
30 {
31 returnx;
32 }// endmethodgetX
33
34 // gety coordinate
35 publicintgetY()
36 {
37 returny;
38 }// endmethodgetY
39
40 // returnStringrepresentationof Shape object
41 publicStringtoString()
42 {
43 returnString.format(“(%d,%d)”,getX(),getY());
44 }
45
46 // abstractmethods
47 publicabstractStringgetName();
48 }// endclassShape
1 // ProgrammingChallenge2:TwoDimensionalShape.java
2 // Definitionof classTwoDimensionalShape.
3
4 publicabstractclassTwoDimensionalShape extends Shape
5 {
6 privateintdimension1;
7 privateintdimension2;
8
9 // four-argumentconstructor
10 publicTwoDimensionalShape( intx,inty,intd1,intd2)
11 {
12 super(x,y );
13 dimension1 = d1;
14 dimension2 = d2;
15 }// endfour-argument TwoDimensionalShape constructor
16
17 // setmethods
18 publicvoid setDimension1(int d)
19 {
20 dimension1 = d;
21 }// endmethodsetDimension1
22
23 publicvoid setDimension2(int d)
24 {
25 dimension2 = d;
26 }// endmethodsetDimension2
27
28 // getmethods
29 publicintgetDimension1()
30 {
31 returndimension1;
32 }// endmethodgetDimension1
33

34 publicintgetDimension2()
35 {
36 returndimension2;
37 }// endmethodgetDimension2
38
39 // abstractmethod
40 publicabstractintgetArea();
41 }// endclassTwoDimensionalShape

1 // ProgrammingChallenge2:Circle.java
2 // Definitionof classCircle.
3
4 publicclassCircleextends TwoDimensionalShape
5 {
6 // three-argumentconstructor
7 publicCircle(intx,inty,intradius)
8 {
9 super(x,y,radius,radius);
10 }// endthree-argumentCircleconstructor
11
12 // overriddenmethods
13 publicStringgetName()
14 {
15 return”Circle”;
16 }// endmethodgetName
17
18 publicintgetArea()
19 {
20 return(int)
21 (Math.PI* getRadius()* getRadius());
22 }// endmethodgetArea
23
24 // setmethod
25 publicvoid setRadius(intradius)
26 {
27 setDimension1(radius );
28 setDimension2(radius );
29 }// endmethodsetRadius
30
31 // getmethod
32 publicintgetRadius()
33 {
34 returngetDimension1();
35 }// endmethodgetRadius
36
37 publicStringtoString()
38 {
39 returnString.format(“%s %s:%dn”,
40 super.toString(),”radius”,getRadius());
41 }// endmethodtoString
42 }// endclassCircle
1 // ProgrammingChallenge2:Square.java
2 // Definitionof classSquare.
3
4 publicclassSquare extends TwoDimensionalShape
5 {
6 // three-argumentconstructor
7 publicSquare(intx,inty,intside)
8 {
9 super(x,y,side,side);
10 }// endthree-argumentSquare constructor
11
12 // overriddenmethods
13 publicStringgetName()
14 {
15 return”Square”;
16 }// endmethodgetName
17
18 publicintgetArea()
19 {
20 returngetSide() * getSide();
21 }// endmethodgetArea
22
23 // setmethod
24 publicvoid setSide(intside)
25 {
26 setDimension1(side);
27 setDimension2(side);
28 }// endmethodsetSide
29
30 // getmethod
31 publicintgetSide()
32 {
33 returngetDimension1();
34 }// endmethodgetSide
35
36 publicStringtoString()
37 {
38 returnString.format(“%s %s:%dn”,
39 super.toString(),”side”,getSide());
40 }// endmethodtoString
41 }// endclassSquare
1 // ProgrammingChallenge2:ThreeDimensionalShape.java
2 // Definitionof classThreeDimensionalShape.
3
4 publicabstractclassThreeDimensionalShape extends Shape
5 {
6 privateintdimension1;
7 privateintdimension2;
8 privateintdimension3;
9
10 // five-argumentconstructor
11 publicThreeDimensionalShape(
12 intx,inty,intd1,intd2,intd3)
13 {
14 super(x,y );
15 dimension1 = d1;
16 dimension2 = d2;
17 dimension3 = d3;
18 }// endfive-argumentThreeDimensionalShape constructor
19
20 // setmethods
21 publicvoid setDimension1(int d)
22 {
23 dimension1 = d;
24 }// endmethodsetDimension1
25
26 publicvoid setDimension2(int d)
27 {
28 dimension2 = d;
29 }// endmethodsetDimension2
30
31 publicvoid setDimension3(int d)
32 {
33 dimension3 = d;
34 }// endmethodsetDimension3
35
36 // getmethods
37 publicintgetDimension1()
38 {
39 returndimension1;
40 }// endmethodgetDimension1
41
42 publicintgetDimension2()
43 {
44 returndimension2;
45 }// endmethodgetDimension2
46
47 publicintgetDimension3()
48 {
49 returndimension3;
50 }// endmethodgetDimension3
51
52 // abstractmethods
53 publicabstractintgetArea();
54 publicabstractintgetVolume();
55 }// endclassThreeDimensionalShape
1 // ProgrammingChallenge2:Sphere.java
2 // Definitionof classSphere.
3
4 publicclassSphere extends ThreeDimensionalShape
5 {
6 // three-argumentconstructor
7 publicSphere(intx,inty,intradius)
8 {
9 super(x,y,radius,radius,radius);
10 }// endthree-argumentShape constructor
11
12 // overriddenmethods
13 publicStringgetName()
14 {
15 return”Sphere”;
16 }// endmethodgetName

17
18 publicintgetArea()
19 {
20 return(int)(4* Math.PI* getRadius()* getRadius());
21 }// endmethodgetArea
22
23 publicintgetVolume()
24 {
25 return(int)(4.0/ 3.0 * Math.PI*
26 getRadius()* getRadius()* getRadius());
27 }// endmethodgetVolume
28
29 // setmethod
30 publicvoid setRadius(intradius)
31 {
32 setDimension1(radius );
33 setDimension2(radius );
34 setDimension3(radius );
35 }// endmethodsetRadius
36
37 // getmethod
38 publicintgetRadius()
39 {
40 returngetDimension1();
41 }// endmethodgetRadius
42
43 publicStringtoString()
44 {
45 returnString.format(“%s %s:%dn”,
46 super.toString(),”radius”,getRadius());
47 }// endmethodtoString
48 }// endclassSphere
1 // ProgrammingChallenge2:Cube.java
2 // Definitionof classCube.
3
4 publicclassCubeextends ThreeDimensionalShape
5 {
6 // three-argumentconstructor
7 publicCube( intx,inty,intside)
8 {
9 super(x,y,side,side,side );
10 }// endthree-argumentCubeconstructor
11
12 // overriddenmethods
13 publicStringgetName()
14 {
15 return”Cube”;
16 }// endmethodgetName
17
18 publicintgetArea()
19 {
20 return(int)(6* getSide()* getSide());
21 }// endmethodgetArea
22
23 publicintgetVolume()
24 {

25 return(int)(getSide()* getSide()* getSide());
26 }// endmethodgetVolume
27
28 // setmethod
29 publicvoid setSide(intside)
30 {
31 setDimension1(side);
32 setDimension2(side);
33 setDimension3(side);
34 }// endmethodsetSide
35
36 // getmethod
37 publicintgetSide()
38 {
39 returngetDimension1();
40 }// endmethodgetSide
41
42 publicStringtoString()
43 {
44 returnString.format(“%s %s:%dn”,
45 super.toString(),”side”,getSide());
46 }// endmethodtoString
47 }// endclassCube
1 // ProgrammingChallenge2:ShapeTest.java
2 // Program teststhe Shape hierarchy.
3
4 publicclassShapeTest
5 {
6 // createShape objectsanddisplaytheirinformation
7 publicstatic void main(Stringargs[])
8 {
9 Shape shapes[]= new Shape[ 4];
10 shapes[0]= newCircle(22,88,4);
11 shapes[1]= newSquare(71,96,10);
12 shapes[2]= newSphere(8,89,2);
13 shapes[3]= newCube( 79,61,8);
14
15 // callmethod printonall shapes
16 for(Shape currentShape:shapes )
17 {
18 System.out.printf(“%s:%s”,
19 currentShape.getName(),currentShape);
20
21 if(currentShapeinstanceof TwoDimensionalShape )
22 {
23 TwoDimensionalShape twoDimensionalShape=
24 (TwoDimensionalShape )currentShape;
25
26 System.out.printf(“%s’sarea is%sn”,
27 currentShape.getName(), twoDimensionalShape.getArea());
28 }// endif
29
30 if(currentShapeinstanceof ThreeDimensionalShape )
31 {
32 ThreeDimensionalShapethreeDimensionalShape =
33 (ThreeDimensionalShape )currentShape;

34
35 System.out.printf(“%s’sarea is%sn”,
36 currentShape.getName(),threeDimensionalShape.getArea());
37 System.out.printf(“%s’svolume is%sn”,
38 currentShape.getName(),
39 threeDimensionalShape.getVolume());
40 }// endif
41
42 System.out.println();
43 }// endfor
44 }// endmain
45 }// endclassShapeTest

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

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