Chapter 09
Chapter 09
Often times there is an existing class that provides a basis for an object
that models a specification. However, the existing class may need addi-
tional methods or different implementations of existing methods to more
closely represent the object for the model. For example, consider a disk,
which has circular shape. It is similar to a circle. However, a disk is three-
dimensional and also has a thickness. Rather than create a whole new class
to represent a disk, a class named Disk could extend the Circle class.
A class can have many levels of inheritance. For example, consider the
TIP fne Objectclassis the following class hierarchy:
superclass
of all otherclasses.
The Puck classinherits the Disk class.which inherits the Circle class.The
Circle classis the superclassof Disk. Disk is the subclassof Circle and the
superclassof Puck. Puck is the subclassof Disk.
Diekinherite
Circle
variable;
lhicknees
meLhodo:
eetThickneee - chanqeolhe thickneos.
qelThickneee - reNurnelhe thicknese.
-
volume relurnolhe volumeof Ihe diek,
equalo- overridesfhe equalo} methoAin Circle.
toSlrinq - overrideslhe to)trinq0 meNhodin Circle,
* constructor
* pre: none
* post: A Disk object has been createtl with railius
* anil thickness t.
thickness = U
]
v = super.area0 * thickness;
return (v);
]
if (test0bj.getRaclius0 == super.getRaclius0
&& test0bj.getThickness() == thickness) {
return (true);
] else {
return (fa1se);
]
]
wu*'J:1tlH'JJ;:"?
by the samenamein the Circle
* post: A string
* been returnecl.
representing the Disk object has
class.
public String toString0 {
String iliskString;
]
TheTestDiskapplicationdisplaysthe following output:
D i s k r a d i u s : 10 . 0
Disk surface area: 3l{.0
D i s k u o l u m e :6 . 2 8
Objects are not equal.
The disk has radius t2.O and thickness 0.05.
The disk has radius 12.0 and thickness 0.07.
Create a Puck class that inherits the Disk class. The Puck class should include member variables weighr,
stanclard, dfld vouth. The stanclaril and youth variables should be boolean variables that are
set to either true
or false depending on the weight of the puck. A standardpuck weighs between5 and 5.5ounces.A youth
puck weighs between 4 and 4.5 ounces.Official hockey pucks, regardlessof weight, are one inch-thick with a
three-inch diameter. The Puck classshould also contain membeimethods getWeight0, getDivisiong, which
returns a string stating whether the puck is standard or youth, and equals0 and toStringg, which overrride
the same methods in the Disk class.The Puck constructor should require an argumenifor weight. Be sure
that the constructor initializes other variables to appropriate values as necessary.
Chapter9 Inheritance
and Polymorphism
Polymorphismis an OOP property in which objectshave the ability to
assumedifferent types.In object-orientedprogramming, polymorphism
is basedon inheritance.Becausea subclassis derived from a superclass,
a superclassobjectcan referencean objectof the subclass.For example,
the following statementsare valid becauseDisk inherits Circle:
Circle wafer;
Disk cookie = new Disk(2. 0.5);
wafer = cookie; //wafer now references cookie
clienLcode
6u?ercta55 class
* Music.java
i--^-+ - ^ . , ^ , . u! Li _l _ . q.=..^-.
TILPUI u Jqva.
public static
fnstrument assignlnstrument0 {
String instrumentChoice ;
Scanner input = new Scanner(Systen.in);
ParF^--=.^. h^.n.
Instrument bandMemberl, bandMembe12, bandMember3;
Scanner input = new Scanner(System.in);
String performanceChoice ;
/* assign instruments */
bandMemberl = assignlnstrument0;
bandMenber2 = assignfnstrument0;
bandMember3 = assignlnstrument 0;
System.out.println(bandMemberl bandMernber2+" "
+ b a n d M e m b e r 3+ " \ n " ) ,
while (!performanceChoice.equalslgnoreCase("L')) {
if (performanceChoice.equalslgnoreCase("S")) {
band = new Performance(bandMemberl);
] else if (performanceChoice. equalslgnoreCase ("D') ) {
band = new Performance(bandMemberl,, bandMembe12);
] else { //deEatlt to trio
band = new Performance(bandMemberl, bandMenber2,
bandMenbe13);
]
band. beqin 0 ;
]
]
f Chapter9 Inheritanceandpolymorphism
The assignlnstrumentQmethod declaresan Instrument return type, but
the individual rerurn statementsreturn Vocal,Piccola,and Clarinet types.
The Instrument objectreturned by the method is polymorphic, changing
to whicheversubclassis actually returned.
The Music applicationproducesoutput similar to:
t r l o u l dg o u L i k e t o h e a r a S o l o , a D u e t , a T r i o , o r L e a u e ?d
squankLaLaLa
H o u l d g o u l i k e t o h e a r a S o I o , a D u e t , a T r i o , o r L e a u e ?t
squankLaLaLapeep
L J o u I dg o u l i k e t o h e a r a S o l o , a D u e t , a T r i o , o r L e a u e ?I
The Music application allows the user numerous combinations for select-
ing a band and hearing performances. The code for such an application
would be more complicated and less flexible without the object-oriented
principles of inheritance and polymorphism. Music is versatile because it
takes advantage of inheritance and polymorphism.
ClassWoodwind(inheritsInstrument)
Constructor/Method
Woodwinil(String nane)
ClassClarinet(inheritsWoodwind)
Constructor/Methods
Clarinet(String name)
x constructor
* pre: none
* post: A soloist has been selecteil
public Performance(Instrument s) {
solo = s;
arrangement = solo.makeSounii0 ;
]
andPolymorphism
chapterI Inheritance
C
* constructor
* pre: none
* post: The members of a ciuet h a v e b e e n s e l e c t e d .
x constructor
* pre: none
* post: The members of a trio have been selecteil.
trio 2 = E2;
trio_3 = t3;
arrangetnent = trj-o
_ l.makeSound0 + trio 2.makeSound0
+ trio _ 3. makeSouncl ( ) ;
]
Modify the Music applicationto allow the user to selecta quartet (four band members)in addition to the
other performances.Changesto the Performanceclasswill also be required to provide the option of creat-
ing a quartet.
* Instrunent c1ass.
x constructor
* pre: none
* post: A musician has been assigned to the instrument.
musician = name'
]
The Vocal classis a subclassof Instrument. It provides the body for the
makeSoundQmethod:
/**
x constructor
x pre: none
* post: A singer has been createcl.
*/
public Vocal(String singerName) {
super (singerNarne);
]
/**
* Returns the souncl of the instrumenc.
* pre: none
* post: The souncl maile by the singer.
*/
public String makeSouncl0 {
return ( "LaLaLa" );
]
/**
* Retsurns a String that represents the instrument.
x pre: none
* post: A string representing the singer.
x/
public String toString0 {
return(super.getMusician0 + " sings " +makeSound0 + ".");
]
]
* itloodwind class.
* constructor
* pre: none
* post: A wooclwincl instrument has been createil.
]
)
9 lnheritance
Chapter andPolymarphism E
The Piccoloclassis a subclassof Woodwind.Itoverrides the makeSoundQ
method:
* constructor
* pre: none
* nost: A niccolo has been created..
x constructor
x n?a. n^na
C andpolymoryhism
chapter9 lnheritance
/*x
* Returns a Strinq that represents the instrument.
* pre: none
* post: A string representing the instrument has
* been returned.
Modify the Music application to allow the user to selecta cymbal or drum in addition to the other instru-
ments for the band members.The Music applicationchangeswill require that PercussioryCymbal, and Drum
classesbe created.The Percussionclassshould be an abstractclassthat inherits the Instrument class.The
Cymbal and Drum classesshould inherit the Percussionclass.
/xx
* constructor
* pre: none
* post: A Circle object created. Radius initialized Lo 1.
x/
public Circle 0 {
radius = 1; //default radius
]
...getRadius),setRadius),andotherCircleclassmethods
/**
* Determines if object c is smaller, Ehe same,
* or larger than this Circle object.
* pre: c is a Circle object
* post: -l- has been returned if c is larger than
* this Circle, 0 has been returned if they are the
* sane size, and t has been returned if c is srnaller
* then this Circle.
*/
nrrhlin irt namnaroT^/nLi-.f ^\ {
! q ! + f v r I 9 g v r | L y g ! g f v \ v l J E U L L / l
]
]
W andpolymorphism
chapter9 Inheritance
The TestCircleapplication produces the output:
multiple interfaces A classcan implement multiple interfaces.When more than one inter-
faceis implemented, the interfacenames are separatedby commas in the
classdeclaration.
Modify the Disk classto implement the Comparableinterface.Tr,vodisks are equal when they have the same
thicknessand sameradius,Modify the existing client codeto test the new method.
Modify the Puck classto implement the Comparableinterface.TWopucks are the equal when they have the
sameweight. Modify the existing client code to test the new method.
Modify the Rectangleclassto implement the Comparableinterface.TWorectanglesare the equal when they
have the samewidth and height. Modify the existing client code to test the new method.
Employee\?ay\QuiN
Enberchoice:E
Enter emVloyeenumber(1,2,or 3): 2 KylieWalNer,
aosociale
Employee\?ay\Quii
E n l e rc h o i c e : 7
EnLeremployee number(1,2,or 3): 2
E n t e r t h e h o u r s f o ar s e o c i a t e
o r ? a yp e r i o d f o m
r ana4er:40
KylieWalber,a ssociale
9740.OO
Employee\?ay\Quit
Enlerchoice:Q
The SalesCenter
algorithm:
1. Display a menu of options.
2. Prompt the user for a menu choice.
3. If the user has not selectedto quit, prompt the user to specify
employee1,2, or 3.
4. Perform the action requestedby the user.
5. Repeatsteps1 through 4 until the user has selectedthe option to
quit.
4 chapter9 lnheritanceandpolymorphism
SalesCenterCode Design
The SalesCenterapplication can be modeled with objectsfor a man-
ager and two associates. The manager and associateobjectsare both
employee objects.Therefore,an Employee abstract class should be used
for subclassesManager and Associate.The Employeeclassshould define
an emplyee'sfirst and last name and include an abstract class for calcu-
lating pay.A manager'spay is basedon a pay period specifiedin weeks.
Associatesare paid by the hour. The absrract pay0 method in Employee
will have different implementations in Manager and Associate.
The SalesCenterclassdesigns are:
EmVloyee
variableotfir eNN
ame.I aeNN
ame
mef,hods:
pay- abetracNclaee.thould return an employee'e
Vayfor a oVecifiedperiod.
No)Nrinq- rel,urnea 6t?in0wibhemployeefirst and laet
name5,
ManaqerexlendsEmploy
ee
yearly1alary
variable:
methodot
-
7el)alary relurns the yearlyoalary.
-
?ay returneamounN earnedbased onNheyearly oalary
and lhe epecifiedperiod.Requireoa ?aramelerfor
Nheweeksin Nhepay period.
lo)tring - returnsa 6trinqwilh employee nameand title,
meLhodet
qeNRate- reLurnsLhe hourlypay rale,
pay - relurns amounl earnedbasedon the hourlypay raLe
and the epecifiedhours.Requireoa paramelerfor
houreworked,
lo)trinq - relurns a elrinq wilh employeenameand tille,
and Polymorphism
Chapter9 tnheritance @
Basedon the algorithm and the class designs,the salescenter cod.e
-
design will include a loop. The pseudocode for ihe salesCenter client
code
follows:
import java. util. Scanne.x;
i-mport java. text. NumberFormaU
payEmployee(emp, payArg) {
System. out. println ( enp ) ;
pay = enp.pay(payArg);
Systern. out. println (pay) ;
]
if (nor quir)
{
prompt user for employee number L, 2, or 3
get empNurn
swirch (empNum) {
case l-: ernp = empl- break;
case 2: emp = emp2; break;
case 3: emp = etnp3- break;
)
if (choice == employee)
{
ilisplay employee name anil title;
] else if (choice == pay) {
prompt user for hours or pay periocl;
payEmployee (emp, payArg) ;
]
]
] while (not quit);
]
]
SalesCenterImplementation
The salescenter implementation involves creating four files. Three files
are the classesand one file is the client code.
* F,mnlnwcc
! r ! , y + v j e e e Iass.
e 4 s r
/**
* constructor
* pre: none
* post: An employee has been created'.
/**
* Returns the employee name.
* pre: none
* post: The ernployee name has been returned.
-,,L] i. Stri
rutrrlY rn ru ^v vqu ff r A YT i . - 1
U
) {L
lultrL
/**
* Returns the employee pay.
* pre: none
* post: The employee pay has been returned.
'l
* Manacer e ass.
* constructor
* pre: none
* post: A nanager has been created.
Chapter9 lnheritanceandPolymorphism E
/**
* Returns the manager pay for a specifiecl periocl.
* pre: none
* post: The manager pay for the specifietl periocl
* has been returnecl.
*/
public ilouble pay(double weeks) {
double payEarned;
/**
* Returns the ernployee name anil title.
Pr E , uurrc
* post: The ernployee name and title has been returneil.
*/
public String toStringfl {
return(super.toStrj-ng0 + ", manager");
]
]
* Associate cl-ass.
* constructo!
- pre: none
* post: An associate has been createcl.
q Chapter9 lnheritanceandpolymorphism
/**
* Returus the employee name antl tit1e.
x pre: none
* post: The employee name and title has been returned.
* l
ilouble payArg;
Employee emp = empl' //set to clefault empl
do{
Systern. out. println ( " \uEmployee\\Pay\\0uit" );
System.out.print("Enter choice: ");
act.ion = input.next0;
if (!action.equalslgnoreCase("Q")) {
System.out.print("Enter employee number (1, 2, or 3):");
enpNum = j-nput.nextfnt0;
switch (ernpNum) {
case 1: emp = empl' break;
case 2: etnP = emP2; break;
case 3: emp = emp3' break;
]
if (action.equalslgnoreCase("8")) {
System. out. println ( emp ) ;
] else if (action.equalslgnoreCase("P")) {
System.out.print("Euter tshe hours for associate or
pay periocl for manager: ");
PaYArg = inPut.nextDouble0;
payErnployee (emp, payArg) ;
]
]
] while (!act.ion.equalslgnoreCase("0"));
andPolymorphism E
9 Inheritance
Chapter
TheSalesCenter
application
generates
outputsimilarto:
E m p l o g e e \ P a g \ 0tu i
Enter choice: e
E n t e r e m p l o g e en u m b e r( 1 , 2 , o r 3 ) : l
DiegoHartin, manageF
E m p l o g e e \ P a g \ 0tu i
Enter choice: p
E n t e r e m p l o g e en u m b e r( 1 , 2 , o r 3 ) : 1
Enter the hours for associate or pag period for managerl
DiegoHartin, manageF
$ 2 ,i l 5 . 3 8
Emplogee\Pag\0uit
Enter choice: q
Modify the SalesCenterapplicationto compensateassociates when they have worked more than 40 hours.
Associatesshould be paid their hourly wage when 40 or fewer hours are worked. However,associatesearn
time and a half for hours over 40.For example,an associatepaid $10per hour will earn $300for 30 hours of
work. However/an associateworking 42 hours will earn $400+ $30,or $430.The overtimepay is calculated
as (hours over 40) * (1,5* basehourly rate).