Chapter 6.
Inheritance and Polymorphism
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
1
Shapes Example
— RecalltheshapesexampleinLecture2,Ocean,the OO guy, wrote a class for each of the 4 shapes
— Avoidduplicatecodebyinheritance — Handlespecializationbyoverriding
superclass (more abstract)
Shape
rotate() playSound()
methods
S
S
e
q
q
u
u
a
a
r
r
e
rotate() playSound( )
C
C
e
i
i
r
r
c
c
l
l
e
rotate() playSound( )
T
T
e le
r
r
i
an
ia
n
g
g
l
rotate() playSound( )
A
A
A
a
m
m
m
o
o
o
e
e
e
b
b
b
a
a
rotate() { /p/laaySmoouendb(a)-specific // rotate code
}
playSound() {
// amoeba-specific // sound code
}
A subclass will automatically inherit the members (i.e., instance variables and methods) of its superclass
subclasses (more specific)
2
Inheritance Overview
— Whendesigningwithinheritance,putcommoncodeinaclass and make it the superclass of the other more specific classes (which then become its subclasses)
— InJava,wesaythatasubclassextendsitssuperclass
— Thereexistsaninheritancerelationshipbetweenasubclass and its superclass where the subclass inherits the members (i.e., instance variables and methods) of its superclass
— Asubclasscanalsoaddnewinstancevariablesandmethods of its own, and can override the methods it inherits from its superclass (specialization!)
— Instancevariablesarenotoverriddenbecausetheydon’tneed to be (they don’t define any behavior). A subclass can give an inherited instance variable any value it chooses
3
Example: SuperHero
SuperHero
suit specialPower
instance variables (state)
methods (behavior)
useSpecialPower() putOnSuit()
Ironman
Superman
overriding methods
useSpecialPower() putOnSuit()
Superman doesn’t need any behavior that’s unique, so he doesn’t override any method
Ironman has specific requirements for his suit and special powers, so both useSpecialPower() and putOnSuit() are overridden in the Ironman class
4
Example: Doctor
Doctor
workAtHospital
treatPatient()
public class Doctor {
boolean workAtHospital;
void treatPatient() { /* perform a checkup */ }
}
public class FamilyDoctor extends Doctor { boolean makesHouseCalls;
void giveAdvice() { /* give homespun advice */ }
}
Surgeon
FamilyDoctor
makesHouseCalls
treatPatient()
makeIncision()
giveAdvice()
public class Surgeon extends Doctor {
void treatPatient() { /* perform surgery */ } void makeIncision() { /* make incision */ }
}
5
Example: Doctor
• Howmanyinstancevariablesdoes Surgeon have?
• Howmanyinstancevariablesdoes FamilyDoctor have?
• HowmanymethodsdoesDoctorhave?
• HowmanymethodsdoesSurgeonhave?
• HowmanymethodsdoesFamilyDoctor have?
• CanaFamilyDoctordotreatPatient()?
• CanaFamilyDoctordomakeIncision()?
Doctor
workAtHospital
treatPatient()
Surgeon
FamilyDoctor
makesHouseCalls
treatPatient()
makeIncision()
giveAdvice()
6
Example: Doctor
• Howmanyinstancevariablesdoes Surgeon have? 1
• Howmanyinstancevariablesdoes FamilyDoctor have? 2
• HowmanymethodsdoesDoctorhave?1
• HowmanymethodsdoesSurgeonhave?2
• HowmanymethodsdoesFamilyDoctor have? 2
• CanaFamilyDoctordotreatPatient()?Yes
• CanaFamilyDoctordomakeIncision()?No
Doctor
workAtHospital
treatPatient()
Surgeon
FamilyDoctor
makesHouseCalls
treatPatient()
makeIncision()
giveAdvice()
7
Designing an Inheritance Tree
— Oceanwasaskedtodesignasimulationprogramthat lets user throw a bunch of different animals into an environment to see what happens
— Initially,theprogramshouldsupport6kindsofanimals:
— Newkindsofanimals,however,maybeaddedtothe program at any time
— Oceanbeganbydesigninganinheritancetreefor the animals
8
Designing an Inheritance Tree
1
Look for objects that have common attributes and behaviors
Common attributes:
food hunger location
Common behaviors:
makeNoise() eat()
sleep() roam()
9
Designing an Inheritance Tree
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
2
Design a class that represents the common state and behavior
Using inheritance avoids duplicating code in the subclasses
Hippo
Dog
Wolf
Cat
Tiger
Lion
10
Designing an Inheritance Tree
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
3
Decide if a subclass needs behavior that is specific to that particular subclass type
H
H
o
i
i
p
p
p
p
o
makeNoise() eat()
D
D
g
o
o
g
makeNoise() eat()
W
W
f
o
o
l
l
f
makeNoise() eat()
C
C
t
a
a
t
T
T
r
i
ge
ig
e
r
makeNoise() eat()
L
L
n
i
i
o
o
n
makeNoise() eat()
makeNoise() eat()
11
Designing an Inheritance Tree
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
4
Look for more opportunities to use abstraction, by finding 2 or more subclasses that might share common behavior
Hippo
makeNoise( )
makeNoise()
eat()
eat()
Dog
makeNoise()
makeNoise()
eat()
eat()
Wolf
makeNoise( )
makeNoise()
eat()
eat()
Cat
makeNoise( )
makeNoise()
eat()
eat()
Tiger
makeNoise( )
makeNoise()
eat()
eat()
Lion
makeNoise()
makeNoise()
eat()
eat()
12
Designing an Inheritance Tree
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
4
Look for more opportunities to use abstraction, by finding 2 or more subclasses that might share common behavior
Canine
roam()
Feline
roam()
Hippo
makeNoise()
makeNoise()
eat()
eat()
Dog
makeNoise()
makeNoise()
eat()
eat()
Wolf
makeNoise()
makeNoise()
eat()
eat()
Cat
makeNoise()
makeNoise()
eat()
eat()
Tiger
makeNoise( )
makeNoise()
eat()
eat()
Lion
makeNoise()
makeNoise()
eat()
eat()
13
Which method is called?
— TheWolfclasshas4methods:1inheritedfrom Animal, 1 inherited from Canine, and 2 overridden in the Wolf class
— Whichversionofthesemethodswillgetcalled when they are called on a Wolf reference?
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
Wolf w = new Wolf(); w.makeNoise(); w.roam();
w.eat();
w.sleep();
Canine
roam()
Wolf
makeNoise()
makeNoise()
eat()
eat()
14
Which method is called?
— TheWolfclasshas4methods:1inheritedfrom Animal, 1 inherited from Canine, and 2 overridden in the Wolf class
— Whichversionofthesemethodswillgetcalled when they are called on a Wolf reference?
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
Wolf w = new Wolf(); w.makeNoise(); w.roam();
w.eat();
w.sleep();
Canine
roam()
Wolf
makeNoise()
makeNoise()
eat()
eat()
15
Which method is called?
— Whenamethodiscalledonanobject reference, the most specific version of the method for that object type will be called
— Inotherwords,thelowestoneinthe inheritance tree wins!
— IncallingamethodonareferencetoaWolf object, the JVM starts looking first in the Wolf class
— IftheJVMdoesn’tfindaversionofthe method in the Wolf class, it starts walking up the inheritance hierarchy until it finds a match
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
Canine
roam()
Wolf
makeNoise()
makeNoise()
eat()
eat()
16
Which method is called?
— Itispossibletocallanoverriddenmethod of the superclass using the keyword super
— Example
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
public class Animal { public void roam() {
System.out.println(“Animal roams”); }
// …
}
Canine
roam()
public class Canine extends Animal { public void roam() {
super.roam(); // roam() in Animal class is called
System.out.println(“Canine roams”); }
}
Wolf
makeNoise()
makeNoise()
eat()
eat()
17
Which method is called?
— Example
Animal
food
hunger location
public class SuperTestDrive {
public static void main(String[] args) {
Canine c = new Canine();
c.roam(); }
}
makeNoise() eat()
sleep() roam()
Canine
roam()
— Sampleoutput
Animal roams Canine roams
Wolf
makeNoise()
makeNoise()
eat()
eat()
18
Access Control
— Asuperclasscanchoosewhetherornotitwantsa subclass to inherit a particular member by the access level assigned to that particular member
— publicmembersareinherited
— privatemembersarenotinherited
— Whenasubclassinheritsamember,itisasifthe subclass defined the member itself
— Aprivateinstancevariableofthesuperclass,which is not inherited, may still be accessed through the inherited public getter and public setter
19
Access Control
Access level
Access modifier
Class
Package
Sub- class
World
private
private
Y
N
N
N
default
(none)
Y
Y
N
N
protected
protected
Y
Y
Y
N
public
public
Y
Y
Y
Y
more restrictive
less restrictive
• privatemeansthatonlycodewithinthesameclasscan access it
• defaultmeansthatonlycodewithinthesamepackageas the class with the default member can access it
• protectedworksjustlikedefaultexceptitalsoallows subclasses outside the package to inherit the protected member
• publicmeansanycodeanywherecanaccessit
20
IS-A Relationship
— Whenoneclassinheritsfromanother,wesaythe subclass extends its superclass
— RecallthatthereexistsaIS-Arelationshipbetweena subclass and its superclass: a subclass object IS-A superclass object (which means a subclass object can do anything that a superclass object can do)
— Tocheckwhetheronething,sayX,shouldextend another, say Y, apply the IS-A test: check if it makes sense to say X IS-A Y?
— Examples:
— TriangleIS-AShape(TriangleextendsShape)
— SurgeonIS-ADoctor(SurgeonextendsDoctor)
21
IS-A Relationship
— TheIS-Atestworksanywhereinthe inheritance tree
— IfclassBextendsclassA,andclassCextends class B, then class C passes the IS-A test for both class B and class A
— Example
— WolfIS-ACanine(WolfextendsCanine)
— CanineIS-A(n)Animal(CanineextendsAnimal) — WolfIS-A(n)Animal(WolfextendsAnimal)
— NotethattheIS-Arelationshipworksinonly one direction!
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
Canine
roam()
Wolf
makeNoise()
makeNoise()
eat()
eat()
22
HAS-A Relationship
— Whatabout“TubextendsBathroom”?
— TocheckwhetherTubshouldextend Bathroom, ask the question: “Does it make sense to say Tub IS-A Bathroom?”
— “TubIS-ABathroom”isdefinitelyfalse,
and therefore Tub should not extend Bathroom
— TubandBathroomarejoinedbyaHAS-Arelationship
— “BathroomHAS-ATUB”meansthatBathroomhasaTub instance variable
23
Rules in Inheritance Design
— Whendesigningwithinheritance
— DOuseinheritancewhenoneclassisamorespecific
type of a superclass
— DOconsiderinheritancewhencommonbehavior should be shared among multiple classes of the same general type
— DONOTuseinheritancejustforreusingcodefrom another class if the relationship between the subclass and superclass violates either of the above 2 rules
— DONOTuseinheritanceifthesubclassandthe superclass do not pass the IS-A test
24
Method Overriding
— RecallthatasubclassobjectIS-Asuperclassobject, and it can do anything that the superclass object can do
— Whenasubclassoverridesamethodinheritedfrom its superclass, it must make sure that
— Argumentlistmustbethesame
— Returntypemustbecompatible(i.e.,eitherthesame
type or a subclass type)
— Themethodcannotbelessaccessible(i.e.,eitherthe same or friendlier access level)
25
— Example
Method Overriding
public class Dog {
public void makeNoise() {
System.out.println(“Woof!”); }
}
public class Poodle extends Dog { public void makeNoise() {
System.out.println(“Ruff! Ruff!”); }
}
26
— Example
same argument lists
Method Overriding
public class Dog {
public void makeNoise() {
System.out.println(“Woof!”); }
}
same access levels
public class Poodle extends Dog { public void makeNoise() {
System.out.println(“Ruff! Ruff!”); }
}
same return types
27
Method Overloading
— Method overloading is nothing more than having 2 or more methods with the same name but different argument lists
— Ithasnothingtodowithinheritanceand polymorphism
— Foroverloadedmethods
— Argumentlistsmustbedifferent — Returntypescanbedifferent
— Accesslevelscanbedifferent
28
Method Overloading
— Example
public class Dog {
public void makeNoise() {
System.out.println(“Woof!”); }
}
public class Poodle extends Dog { public void makeNoise(int n) {
for (int i = 0; i < n; i++) { System.out.println("Ruff! Ruff!");
} }
}
29
— Example
Method Overloading
different argument lists
public class Dog {
public void makeNoise() {
System.out.println("Woof!"); }
}
public class Poodle extends Dog { public void makeNoise(int n) {
for (int i = 0; i < n; i++) { System.out.println("Ruff! Ruff!");
} }
}
30
Benefits of Inheritance
— Getridofduplicatecode
— Behaviorscommontoagroupofclassesare
abstracted out and put in a superclass
— Onlyoneplacetoupdatewhenmodificationsofthese
common behaviors are needed
— InJava,allclassesthatextendthesuperclasswill automatically use the new version. Hence no need to touch the subclasses, not even recompiling them!
31
Benefits of Inheritance
— Defineacommonprotocolforagroupofclasses
— Establishesacontractwhichguaranteesallclasses that extend a superclass have all the inheritable methods of that superclass
— Allowsanysubclassobjectbesubstitutedwherethe superclass object is expected (i.e., polymorphism)
— Example:
Animal animal1 = new Dog(); Animal animal2 = new Cat();
32
The WayPolymorphism Works
— The3stepsofobjectdeclaration,creationand assignment
1. Declareareferencevariable
2. Createanobjectontheheap
3. Assigntheobjectreferencetothevariable 123
Dog myDog = new Dog();
Dog
object
2
Create a Dog object on the heap
1
Declare a reference variable Dog
3
Assign the object reference to the variable
Here, both the reference type and the object type are the same (i.e., both are Dog)
33
The WayPolymorphism Works
— Withpolymorphism
— Thereferencetypecanbeasuperclassoftheactualobject
type
— AnyobjectthatpassestheIS-Atestforthedeclaredtypeof the reference variable can be assigned to that reference variable
Dog
object
The reference variable type is declared as Animal, but the object created is a Dog object
Animal myDog = new Dog();
Animal
34
Benefits of Polymorphism
— Candothingslikepolymorphicarrays,polymorphic argument and polymorphic return types
— Makesitpossibletowritecodethatdoesnothaveto change when new subclass types are introduced
— Example
Animal[] animals = new Animal[6]; animals[0] = new Dog(); animals[1] = new Cat(); animals[2] = new Wolf(); animals[3] = new Hippo(); animals[4] = new Lion(); animals[5] = new Tiger();
for (int i = 0; i < 6; i++) { animals[i].makeNoise (); animals[i].eat();
}
Calling the methods on the actual subclass objects in runtime
35
Benefits of Polymorphism
— Example
public class Vet {
public void giveShot(Animal a) {
// gives shot to the Animal
a.makeNoise(); }
}
public class PetOwner { public void start() {
Vet v = new Vet(); Dog d = new Dog();
Hippo h = new Hippo(); v.giveShot(d); v.giveShot(h);
} }
This will work for future Animal subclasses as well
36
We are with you!
If you encounter any problems in understanding the materials in the lectures, please feel free to contact me or my TAs. We are always with you!
We wish you enjoy learning Java in this class.
37
Chapter 6.
End
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
38