0% found this document useful (0 votes)
84 views26 pages

Chapter 09

The document discusses inheritance and polymorphism in object-oriented programming. It explains that inheritance allows a class to extend an existing class, creating a subclass with an "is-a" relationship to the base class. This provides code reuse and a means for polymorphism. Subclasses can override or extend the behavior of base classes, while still accessing their methods and properties through the super keyword. Inherited methods are called the same way as methods defined directly in the subclass.

Uploaded by

aclivis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views26 pages

Chapter 09

The document discusses inheritance and polymorphism in object-oriented programming. It explains that inheritance allows a class to extend an existing class, creating a subclass with an "is-a" relationship to the base class. This provides code reuse and a means for polymorphism. Subclasses can override or extend the behavior of base classes, while still accessing their methods and properties through the super keyword. Inherited methods are called the same way as methods defined directly in the subclass.

Uploaded by

aclivis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Inheritanceand Polymorphism

\-/bject-oriented programming is basedon a paradigm in which objects


are used to model a specification.Objectsare createdfrom classes,which
provide encapsulation.Inheritanceextendsa classand provides a means
of polymorphism. This chapter discussesinheritance and polymorphism.
Abstractclassesand interfacesare also discussed.

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.

inheritance Making one class an extension of another involves inheritance. Inheritance


allows a class to define a specialized type of an already existing class. In
this case,a disk is a solid circle with a thickness. Classes that are derived
is-arelationship from existing classes demonstrate an is-a relationship. A class "is a" type
of another class. In this case,a disk is a circle with a thickness.

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.

Chapter9 lnheritanceand Polymorphism


extends A class that inherits another class includes the keyword exrends in the
class declaration and takes the form:
public class <name> extenils <cl-ass name> {
<c1ass clefinition>
]
base class Designing a subclassrequires selecting the superclass,or baseclass,
and then defining any additional variable and method members for the
subclass,In many cases,existing methods in the baseclasswill also be
derived class overriddenby new definitions in the subclass,also called the derioedclass.
For example,the Disk classdesignappearssimilar to:

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,

The Disk classimplementation,basedon the designabove,is:


/**
* Disk c1ass.
*/
public class Disk extend.s Circle {
private double thickness;

* constructor
* pre: none
* post: A Disk object has been createtl with railius
* anil thickness t.

public Disk(clouble r, ilouble t) {

thickness = U
]

* Changes the thickness of the disk.


* pre: none
* post: Thickness has been changed.

public void setThickness(double newThickness) {


thickness = newThickness;
]

Chapter9 lnheritanceand Polymorphism


* Returns the thickness of the disk.

* post: The thickness of the disk has been returned.

public double getThickness 0 {


return (thickness);
]

* Returus the volume of the iU-sk.


Prc. uuuc

* post: The volume of the ilisk has beeu returneil.

public tlouble volume0 {


ilouble v;

v = super.area0 * thickness;
return (v);
]

* Determines if the object is equal to another


* Disk object.
* pre: tl is a Disk object.
* post: true has been returueil if objects bave the same
* raclii ancl thickness. false has been returnecl ot.herwise.

public boolean equals(Object d) {


Disk testobj = (Disk)d;

if (test0bj.getRaclius0 == super.getRaclius0
&& test0bj.getThickness() == thickness) {
return (true);
] else {
return (fa1se);
]
]

* Returns a String that represents the Disk object.


* pre: none

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;

cliskString = "The clisk has railius " + super.getRaclius()


+ " ancl thickness " + thickness + ".";
return(cliskString) ;
,
]

super ln a subclass,the keyword =upe. is used to accessmethods of the


base class.For example, the statem€nt super(r) calls the constructor of
the superclass, Circle, and passes an argument for setting the radius
visibility value. Members that are declared privare are not accessibleto derived
classes.Therefore, accessormethods are used to get inherited member
variable values. For example,the equals0 method in the Disk class calls
getRadius0.

Chapter9 lnheritanceand Polymorphism


Inherited methods are called directly from an object,just as any method
of the classis called. whether a method is original to the Disk classor
inherited from the Circle classis transparent to client code,as demonstrated
in the TestDiskapplication:
public class TestDisk {

public static voiil main(String[] args) {


Disk saucer = new Disk(10, 0.02);

System. out. printfn ( "Disk raclius: " + saucer.getRaclius());


Systen. out. println ( "Disk surface area: " + saucer-area());
System. out. println ( "Disk volurne: " +.=',^o-r'^1"-^lll.

Disk p1ate1 = new Disk(12, 0.05);


Disk p1ate2 = new Disk(12, 0.07);
if (platel.equals(p1are2)) {
System. out.println ( "objects are equal. " );
] else {
System. out.println ( "Objects are n o t e q u a l . " ) ;
]
System. out. println (p1ate1) ;
System. out. println (p1ate2 );

]
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.

Createa Hockey application that tests the puck class.

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

The wafe' object, declared a Circle, is polymorphic, as demonstrated in


the statement wafer = cookie where wafer €ISSU[lesthe form of cookie, El
Disk object.

Polymorphism is further demonstrated when the referenced object


determines which method to execute. This is possible when a subclass
overrides a superclass method. In this case,the Disk class has overridden
the equalsQ and toStringQ methods. Because of this, the following state-
ment executes the Disk toStringQ method even though wafer W&s declared
a Circle object:
2.0 and thickness 0.5. */
/* displ-ays: The disk has radius
System. out. println (wafer) ;

To further demonstrate polymorphism, the Music application will


be developedin this section.The Music application allows the user to
assemblea small band. The user can assigna band membereither vocals
(voice)or a woodwind instrument (piccoloor clarinet).The user can then
selectto hear either a solo,duet, or trio performancefrom this band.
The Instrument class,its subclasses, and the Performanceclassare
used to model the objectsfor the Music application.The diagram below
illustratesthe client code and classesfor the Music application.Note the
hierarchyof the Instrument classand its subclasses:

clienLcode

6u?ercta55 class

Chapter9 lnheritanceand Polymorphism


The Music client code is shown below:

* Music.java

i--^-+ - ^ . , ^ , . u! Li _l _ . q.=..^-.
TILPUI u Jqva.

n,rl-rlin .l... M',.i- I

,/* Returns a selected instrumenL.


* pte: none
* nosf: An ins1-rrrment ohiec1- has heen returned.

public static
fnstrument assignlnstrument0 {
String instrumentChoice ;
Scanner input = new Scanner(Systen.in);

System.out.println("Select an instrument for the


band member. " );
System.out.print("Vocals, Piccolo, or Clarinet: ");
instrumentChoice = input.nextline ();
System.out.print("Enter the band member's name: ");
name = input.nextline 0;
if (instrumentChoice.equalslgnoreCase("V")) {
return (new Vocal(name) ) ;
] else if (instrumentChoice.equal-slgnoreCase("P")) {
r e t u r n ( n e w P i c c o l o ( n a m e )) ;
] else { //default to clarinet
return (new Clarinet (nane) ) ;
]
]

nrrhlic qj-^ti. vnirl mai.{St.i.-fl ^--.1 {L

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 " ) ,

System.out.print("Would you like to hear a Sofo, a Duet,


a Trio, or Leave? " );
nerFormanccChni cc = i rnrri- ncvtLi na I )'

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 ;

System.out.print("\nWould you like to hear a So1o,


a Duet, a Trio, or Leave? " );;
ncrfnrnan.och^i.a = inn'rl .-*fLi.-II'

]
]

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:

Se1ect an instrument for the band member.


UocaIs, Piccolo, or Clarinet: c
E n t e r t h e b a n d m e m b e r ' sn a m e : A n t h o n g
Select an instrument for the band membeF.
Uocals, Piccolo, or Clarinet: u
E n t e r t h e b a n d m e m b e r ' sn a m e : L g n
Select an instrument for the band menber.
UocaIs, Piccolo, or Clarinet: p
E n t e r t h e b a n d m e m b e F ' sn a m e : D a n a
Anthong plags squaHk. Lgn sings LaLaLa. Dana plags peep.

blould gou like to hear a Solo, a Ouet, a Trio, or Leaue? s


squank

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.

The documentation for the Instrument, Vocal, Woodwind, Piccolo,


and Clarinet classesis below. Note that the makeSound0 method in the
Instrument class is a method that must be implemented (written) in a sub-
class.This is discussed further in the next section. The code for the classes
is also shown in the next section where abstract classes are discussed.
ClassInstrument
Constructor/Methods
fnstrument(String nane)

an instrument object with musician


:::::"t
setMusician0 returns a string that is the musician's name.
makeSound0 an abstract method that should return a String
representing the instrument's sound.

Chapter9 lnheritanceand Polymorphism


ClassVocal(inherits
Instrument)
Constructor/Methods
Voeal {Stri no name)

createsa singer object with singer name.


makeSounil0 returns the String LaLaLa.
toSrrins0 returns a String that representsthe singer.

ClassWoodwind(inheritsInstrument)
Constructor/Method
Woodwinil(String nane)

createsa woodwind instrument object with


musician tram..
nakeSouncl0 returns the String coot.

Class Piccolo (inheritsWoodwind)


Constructor/Methods
Piccolo (String name)

createsa piccoloistobjectwith musici€lrlname.


makeSounil0 returns the String neen.
rosrrins0 returns a String that representsthe object.

ClassClarinet(inheritsWoodwind)
Constructor/Methods
Clarinet(String name)

createsa clarinetist object with musician name'


nakeSound0 returns the String squawk.
roStrins0 returns a String that representsthe object'

The Performanceclasscreatesan arrangementof Instrument objects.


The constructors require Instrument arguments, but polymorphism
enablesobjectsof Instructor subclassesto be passed:
/**
* Perfornance class.
*/
public class Performance {
n (f -^ arrandamanr'
y f- ri vr r r f aq u E r.

private Instrunent solo;


private Instrument cluet - 1, duet - 2;
nrivate Tnstrument trio 1, trio 2, trio 3;

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 .

public Performance (Instrument cll-, Instrunent il2) {


duet_1= cl1;
duet_2 = d2;
arrangement = cluet_1.makeSound0 + tluet 2.makeSouncl();
]

x constructor
* pre: none
* post: The members of a trio have been selecteil.

public Perforrnance (Instrunent t1, Instrunent t2,


fnst-rrrnent t3) {
'l -
tsri^ ts1.

trio 2 = E2;
trio_3 = t3;
arrangetnent = trj-o
_ l.makeSound0 + trio 2.makeSound0
+ trio _ 3. makeSouncl ( ) ;
]

* Begins the performance.


x pre: none
* post: The performance has been playetl.

public void begin0 {


System. out. println ( arrangement) ;
]

* Returns a String that represents per€ormers.


the
* pre: none
* post: A string representing the perforrners has
* been returnecl.

public String toString0 {


String program = "The performance inclucles ";
program += arrangement;
return (progran) ;
]

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.

Chapter9 Inheritanceand Polymorphism


An abstractc/assmodels an abstractconcept.For example,a musical
instrument is an abstract concept.An instrument is something that can
be played, but there is no such thing an "instrument" instrument. There
are however,flutes, piccolos,drums, and cymbals.
Abstractclassescannotbe instantiatedbecausethey should not repre-
sent objects.They instead describe the more general details and actions
of a type of object. For example,the Instrument class describesthe very
basicsof an instrument-it can make a sound.The Woodwind classis also
an abtractclassbecauseit describesa group of instruments.It includesa
generalsound that woodwind instrumentsmake.
abstract Abstract classesare declaredwith the keyword absrracr in the class
declaraction. They are intended to be inherited. The public members of
the abstractclassare visible to derived objects.However, an abstractclass
abstract method can also contain an abstractmethod. An abstractmethodis declaredwith
the keyword absrracr and contains a method declaration,but no body.
The abstractclassmust be implementedin its subclass.
The Instrument classis an abstractclasswith an abstractmethod. The
makeSoundQmethod must be implemented in an Instrument subclass:

* Instrunent c1ass.

abstract class Instrument {


Sr-i.- mrrciniar'

x constructor
* pre: none
* post: A musician has been assigned to the instrument.

nrrhl i n Trcf?rlmanf lqfri nd -^--\ {

musician = name'
]

* Returns the name of the musician


* pre: none
* post: The name of the musician playing the instrument
* has been returnetl.

public String getMusician() {


return (musician);
]

* Shoulii return the sounil of the instrumenc.


* pre: none
* post: The sound macle by the instrument is returned..

abstract String makeSound ( ) ;


)

The Vocal classis a subclassof Instrument. It provides the body for the
makeSoundQmethod:

Chapter 9 lnheritance and Polymorphism


/**
* Vocal c1ass,

public class Vocal extencls Instrument {

/**
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 + ".");
]
]

The Woodwind classis also an Instrument subclass.It too implements


the makeSoundQ method. However, Woodwind describes a group of
instruments so it has also been declared abstract:

* itloodwind class.

abstract class Wooclwincl extencls Instrument {

* constructor
* pre: none
* post: A wooclwincl instrument has been createil.

public Wooclwincl(String player) {


super(player);
]

* Returns the souncl of the instrument.

* post: The sound macle by the instrument is returned..

public String nakeSouocl() {


rarrr?r I urnatu l.

]
)

9 lnheritance
Chapter andPolymarphism E
The Piccoloclassis a subclassof Woodwind.Itoverrides the makeSoundQ
method:

* Piccolo class. ..-_-./

public class Piccolo extenils t'lootlwincl {

* constructor
* pre: none
* nost: A niccolo has been created..

public Piccolo(String piccoloist) {


super (piccoloist) ,
]

* Returns the souncl of the instrumeat.


* pre: none
* post: The souncl maile by the instrument is returnecl.

public String rnakeSounil0 {


TAf rr ?n t '
E'YE

* Returns a String that represents the iastrument.


* pre: none
* post: A string representing the instrument has
* been returneil.
*/
public String toString0 {
return(super.getMusician0 + " plays " +makeSound0 + ".");
]
I

The Clarinet class is also a Woodwind subclass.It too overrides the


makeSound0 method:
/**
* Clarinet class.
*/
public class Clarinet extends Woodwind {

x constructor
x n?a. n^na

* post: A clarinet has been createil.

public Clarinet(String clarinetist) {


super (clarinetj-st);
]

* Returns the sound of the instrument.


* nro. -^-o

* post: The sounil macle by t.he instrument is returneil.

public String rnakeSouncl0 {


return ( "squawk" );
]

C andpolymoryhism
chapter9 lnheritance
/*x
* Returns a Strinq that represents the instrument.
* pre: none
* post: A string representing the instrument has
* been returned.

nrrhlin (rrinn f^qrrindf)


q v v 9 + + . r Y f
\ , l

return(super.getMusicianfl + " plays " +makeSoundfl + ".");


]
]

Through inheritanceand abstraction,a hierarchyof classescan be cre-


ated that begin with a general abstraction and lead to a specific object.

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.

Aninterfaceis a classwith method declarationsthat haveno implemen-


tations.Although an interfacemay seemsimilar to an abstractclass,it is
very different. An interfacecannot be inherited. It may only be imple-
mentedin a class.An interfacecan add behaviorto a class,but it doesnot
provide a hierarchyfor the class.
An interface takes the form:
<access _ level-> interface <name> {
(<rnethod
<return _ type> <nethocl _ name> _ param>);
...additional
methods
]

The methods defined in an interfaceare by default public and abstract.


Therefore,the methods in an interface are only declarations followed by
a semicolon.

Comparahleinterface The Comparableinterfaceis part of the java.langpackage.It contains


one method:
InterfaceComparable (java.lang.Com
parable)
Method
compareTo (Object obj )

returns 0 when obi is the same as the object,


a negative integer is returned when obj is
less than the object, and a positive integer is
returned when ob5 is greater than the object.

When an interface is implemented in a class, the class must implement


each method defined in the interface. In this case,the Comparable interface
contains just one method. The Circle class shown on the next page has
been modified to implement the Comparable interface.

Chapter9 lnheritanceand Polymorphism


* Circle class.

public class Circle implements Comparable {


private static final double Pf = 3.14;
private double radius;

/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

Circle testCircle = (Circle)c;

if (radius < testCircle.getRadius0) {


return (-l-) ;
] else if (radius == testCircle.getRadius0) {
return(0);
] else {
return (1),
]
]

The TestCircleclient codeteststhe compareTo0method:

* The Circl-e class is tested.

public class TestCircle {

public void main(String[]


static args) i
Circle spotl- = new Circle(3);
Circle spot2 = new Circle(4);
if (spotl.compareTo(spot2) == 0) {
Systen.out.prj-ntln("Objects are equa1.");
] else if (spotl.compareTo(spot2) < 0) {
System.out.println("spot1 is smaller than spot2.");
] ^1.. i
System.out.println("spotJ- is larger than spot2.");
]
(-'oto- ^,,f hri nrl r lenarT \.

Srrcfon ^,,f nri.t1. l.^^t?1.

]
]

W andpolymorphism
chapter9 Inheritance
The TestCircleapplication produces the output:

spotl is smaller than spotz.


Circlc has radius 3.0
Circlc has radius 4.0

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.

Createan interfacenamed ComparableAreathat containsone method named compareloAreaQ.This method


should return 0 when the objecthas the samearea as another object,-1 should be returned when the object
has an area less than another object,and L returned otherwise.
Modify the Rectangleclassto implementthe ComparableAreainterfaceas well as the Comparableinterface
implemented in the previous review. Modify the existing client code to test the new method.

In this casestudy,a salescenterapplicationwill be created.The sales


centerhas three employees,which include a manager and two associates.
The manager earns a salary and the associatesare paid by the hour. The
owner of the salescenterwants a computerapplicationto display employee
information and calculatepayroll.

Chapter9 Inheritanceand Polvmorphism


SalesCenterSpecification
The SalesCenterapplication storesinformation about three employees.
Thereis one manager(DiegoMartin, salary $51000),and two associates
(Kylie Walter earning $18.50per hour and Michael Roseearning $I67s
per hour). SalesCentershould be able to display the name and title for
a specified employee.Additionally, the SalesCenterapplication should
calculate and display the pay for a specified employeebased on the pay
argument enteredby the user.The pay argument should correlateto hours
worked if the pay for an associateis to be calculated.The pay argumenr
for a manager should correlateto the number of weeks the manager is to
be paid for.
The SalesCenterinterfaceshould provide a menu of options. Depending
on the option selected,additional input may be needed.The SalesCenter
output sketch:

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,

As sociate exlends Employee


variable: hourly1ayKat
e

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

public class SalesCenter {

payEmployee(emp, payArg) {
System. out. println ( enp ) ;
pay = enp.pay(payArg);
Systern. out. println (pay) ;
]

public sraric voicl nain(String[] args) {


llanager empl = new Manager ( "Diego", ,'Martin,,, 55000 ) ;
Associate ernp2 = new Associate(,,Kyl:_e,', ,,Walter,,.
19.50);
Associate ernp3 = new Associate(',Michae1',, ,,Rose,,,
t6.751;
Enployee emp = emp1. //d.efatttt employee choice

/* display menu of choices */


do{
prompt user for employee/pay/quit
get user choice;

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.

Chapter9 Inheritanceand polymorphism


The Employeeclassis implemented below:

* F,mnlnwcc
! r ! , y + v j e e e Iass.
e 4 s r

abstract class Employee {


q+-i -- €i -^FNT-ma I --rT\I^-o.
rLrru9

/**
* constructor
* pre: none
* post: An employee has been created'.

public Employee(String fName, String lName) {


firstName = fName;
lastName = lName;
]

/**
* 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

return(firstName + " " + lastNarne);


]

/**
* Returns the employee pay.
* pre: none
* post: The employee pay has been returned.

abstract double pay(double period);


]

The Managerclassis implementedbelow:

'l
* Manacer e ass.

class Manager extenils Employee {


double yearlySalary;

* constructor
* pre: none
* post: A nanager has been created.

public lvlanager(String fName, String 1Name, double sa1) {


super(fName, lName);
yearlySalary = sal;
]

* Returns the manager salary,


* pre: none
* post: The manager salary has been reLurned.

public clouble getSalary0 {


return (yearlySalary) ;
]

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;

payEarnetl = (yearlySalary / 521 * weeks;


return (payEarnecl);
]

/**
* 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");
]
]

The Associateclassis implemented below:

* Associate cl-ass.

class Associate extencls Employee {


tlouble hourlyPayRate;

* constructo!
- pre: none
* post: An associate has been createcl.

public Assoclate(String fName, String lNarne, ilouble rate) {


super(fName, lName);
hourlyPayRate = rate;
]

* Returns the associate pay !ate.


* pre: none
* post: The associate pay rate has been returneil.

public clouble getRate 0 {


return (hourJ-yPayRate ) ;
)

* Returns the associate pay for the hours workecl.


x nro. nnna

* post: The associate pay for the hours .workecl


* has been returned-

public ilouble pay(clouble hours) {


clouble payEarneil;

payEarnecl = hourlyPayRate * hours;


return (payEarnecl);
l

q Chapter9 lnheritanceandpolymorphism
/**
* Returus the employee name antl tit1e.
x pre: none
* post: The employee name and title has been returned.
* l

^,,L1i^ qF-;-^ tL sU e^Lqr r + ri-^ll IL


Pqlfre sLrfug uy v

return(super.toString0 + ", associate");


]
]

The SalesCenterclient code is implemented below:


inport java. uti1. Scanner;
inport java.text. NumberFormat;

public class SalesCenter {

* Displays employee name ancl pay.


* pre: none
* post: Ernployee name and pay has been ilisplayed

public static voiil payEnployee(Enployee emp, clouble payArg) {


NunberFormat money = NurnberFormat. getCurrencylnstance 0 ;
clouble pay;

Systern. out. priotln ( emp ) ;


pay = enp.pay(payArg);
System. out. println (noney. format (pay) ) ;
]
public static voicl nain(Stringl] args) {
Manager empl = nev llanager("Diego","ltartin", 55000);
Assoclate enp2 = new Assocl-ate("Ky1ie", "Wa1ter", 18.50);
Associate emp3 = new Associate("Michael", "Rose", 16.75);
Scanner input = new Scanner(System.in);
String actlon;
r -! ^*-1T.. - .
f uu ErtrPrr utrL,

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

SalesCenterTesting and Debugging


Client codeshould first be written to test eachclass.Testingshould be
done for the client code.

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

This chapterdiscussedinheritanceand polymorphism, two key aspects


of object-orientedprogramming.Inheritanceallows classesto be derived
from existing classes.By extending an existing class,there is lessdevel-
opmentand debuggingnecessary. A classderived from an existing class
demonstratesan is-a relationship.
A superclass is alsocalleda baseclass,and a subclassis calleda derived
class.The keyword exrendsis used to createa derived classfrom a base
class.The keyword superis used to accessmembersof a baseclassfrom
the derived class.
Polymorphism is the ability of an object to assumedifferent types. In
OOP,polymorphism is based on inheritance,An object can assumethe
type of any of its subclasses.
Abstractclassesmodel abstractconcepts.They cannotbe instantiated
becausethey should not representobjects.An abstractclassis intended
to be inherited.

Chapter9 lnheritanceand Polymorphism


Abstract classesmay or may not contain abstract methods. An abstract
method is a method declaration with no implementation. If a class con-
tains one or more abstract methods, it must be declared abstract. Abstract
methods must be implemented in a class that inherits the abstract class.

An interface is a class that contains only abstract methods. An interface


can be implemented by a class, but it is not inherited. A class that imple-
ments an interface must implement each method in the interface. The
Comparable interface is part of the java.lang package and is used to add
a compareToQ method to classes that implement the interface.

Chapter9 lnheritanceand Polymorphism


Abstract class A class that models an abstract
concept.A classthat contains one or more abstract
methods must be declared abstract.
Abstract method A methodthat hasbeendeclared,
but not implemented. Abstract methods appear in
abstractclasses.They are implemented in a subclass
that inherits the abstractclass.
Baseclass A superclass.
Derived classA subclass.
Inheritance The OOP property in which a class
can define a specializedtype of an already exist-
ing class.
Interface A classwith abstractmethods.An inter-
facecannot be inherited, but it can be implemented
by any number of classes.
Is-a relationship The relationship demonstrated
by a classderived from an existing class.
Polymorphism TheOOPpropertyinwhichobjects
have the ability to assumedifferent types.

absrracr The keyword used for declaring a class


or a method as abstract.

Comparable A java.lang interface with the


compareTo0 method that can be implemented in
classes to provide a means for an object to be com-
pared to another object of the same type.

exrenils The keyword used in a class declaration to


inherit another class.

interface The keyword used in a class declaration


to declare it an interface.

super The keyword used to call a superclass con-


structor or method.

Chapter9 lnheritanceand Polymorphism


1 . Explain the difference between a has-a and is-a e) How doesthe implementation of doThis0 in
relationship among classes. Roo affect the implementation of dolhis0 in
Bo?
2. If a base class has a public method go0 and a f) What action does the statementsuper(l) in
derived class has a public method stopQ, which Roo perform?
methods will be available to an object of the g) Can the doThis0 method in Bo be called
derived class? from a Roo object?If so, how?
h) Can a method in Roo call the doThis0
3. Compare and contrast implementing an abstract method in Bo?If so.how?
method to overriding a method.
True/False
A
Compare and contrast an abstract class to an
interface. 7. Determine if eachof the following are true or
false.If false,explain why.
5. List the method(s) contained in the Comparable a) Inheritanceallows a classto define a special-
interface. ized type of an already existing class.
b) Classesthat are derived from existing classes
6. Use the following classesto answer the questions demonstratea has-arelationship.
below: c) A class can have only one level of
inheritance.
interface lJo {
d) A classthat inherits another classincludes
nnh'l i n i.t .i^Tl'=t 1l .
the keyword inherirance in the class
]
declaration.
nll].ti. .t^.. R^ {
e) When implementing a subclass,existing
nri\r^fa ihf v'
methods in the base class can be
overridden.
X=z; f) Members of a base class that are declared
] private are accessibleto derived classes.
g) Inherited methods are called directly from
public int doThis 0 { an object.
return(2);
h) Polymorphism is an OOP property in which
]
objectshave the ability to assume different
public i n t d o N o w0 { types.
return (15); i) Abstractclassescan be instantiated.
] j) An abstractclassmust be implemented in its
] subclass;
public class Roo extends Bo implements Wo { k) An abstract method contains a method
public Roo {
declarationand a body.
super (1) ; l) Inheritanceand abstractionallow a hierarchy
] of classesto be created.
m) An interface can be inherited.
public int iloThis() { n) An interfacecan add behavior to a class.
return(10);
o) The methods defined in an interfaceare pri-
]
vate by default.
private int doThat0 { p) The Comparable interface contains three
return(20); methods.
)
]
a) What type of method is doThat0 in Wo?
b) What is Wo?
c) Why is doThatQimplemented in Roo?
d) List the methods availableto a Roo object.

Chapter9 Inheritanceand Polymorphism


Exercise I UEmployee, Faculty, Staff
Createa UEmployeeclassthat containsmembervariablesfor the university employeename and salary.
The UEmployee classshould contain member methods for returning the employeename and salary.
CreateFaculty and Staff classesthat inherit the UEmployeeclass.The Faculty classshould include
membersfor storing and returning the departmentname.The Staff classshould include membersfor
storing and returning the job title.

Exercise 2 Account, PersonalAcct,BusinessAcct


CreatePersonalAcctand BusinessAcctclassesthat inherit the Account classpresentedin Chapter 8.
A personalaccountrequiresa minimum balanceof $100.If the balancefalls below this amount, then
$2.00is charged(withdrawn) to the account.A businessaccountrequiresa minimum balanceof $500,
otherwise the accountis charged$10.Createclient codeto test the classes.

Exercise 3 Vehic1e,Car, Truck, Minivan


Createa Vehicleclassthat is an abstractclassdefining the generaldetails and actionsassociatedwith
a vehicle.CreateCar, Truck, and Minivan classesthat inherit the Vehicleclass.The Car, Truck, and
Minivan classesshould include additional membersspecificto the type of vehiclebeing represented.
Createclient codeto test the classes.

Chapter9 Inheritanceand Polymorphism

You might also like