Chapter 7.
Abstract Classes and Interfaces
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
The Animal Inheritance Tree
¡ª Recalltheinheritancetreeforanimals
¡ª Keepduplicatecodetoaminimum
¡ª Overridemethodsforsubclassspecific implementations
¡ª Niceandflexiblefromapolymorphic perspective
Animal
food
hunger location
makeNoise() eat() sleep() roam()
Canine
roam()
Feline
roam()
Hippo
makeNoise() eat()
Dog
makeNoise() eat()
Wolf
makeNoise() eat()
Cat
makeNoise() eat()
Tiger
makeNoise( ) eat()
Lion
makeNoise() eat()
2
The Animal Inheritance Tree
¡ª Examples of instantiating a class from the tree Wolf
object
A Wolf reference to a Wolf object
Hippo
Wolf aWolf = new Wolf();
Wolf
Animal aHippo = new Hippo();
Animal
object
An Animal reference to a Hippo object
Animal
What does an Animal object look like?
3
Animal anim = new Animal();
object
An Animal reference to an Animal object
Animal
Abstract Class
¡ª ItmakessensetocreateaWolfobject,aHippoobjector a Tiger object
¡ª WhatexactlyisanAnimalobject?Howdoesitlooklike? What is its shape, color and size? How many legs…
¡ª TheAnimalclassisneededforinheritanceand polymorphism
¡ª Programmers are, however, supposed to instantiate only the less abstract subclasses of the Animal class, but not the Animal class
¡ª Asimplewaytopreventaclassfromeverbeing instantiated is by marking it as abstract
4
Abstract Class
¡ª Thekeywordabstractisusedtodefineanabstractclass
abstract class Canine extends Animal { public void roam() { … }
}
¡ª Thecompilerwillstopanyonefrominstantiatinganabstract class using the new operator
¡ª Anabstractclasscanbeusedasareferencetype(e.g.,usingit as a polymorphic argument or return type, or to make a polymorphic array)
¡ª Whendesigninganinheritancetree,onemustdecidewhich classes are abstract and which are concrete (concrete classes are those that are specific enough to be instantiated)
5
Abstract Class
¡ª Example:Whichclassesareabstract/concrete? abstract
Animal
abstract
Feline
concrete
abstract
Canine
concrete
concrete concrete
concrete
Cat
Hippo
Lion
Dog
concrete
Wolf
Tiger
6
Abstract Method
¡ª Besidesclasses,methodscanalsobemarkedasabstract
¡ª Anabstractclassmeanstheclassmustbeextended,whereas
an abstract method means the method must be overridden ¡ª Anabstractmethodhasnomethodbody,justendswitha
semicolon
¡ª Aclassmustbemarkedasabstractifithasatleastone abstract method. It is illegal to have an abstract method in a non-abstract class!
¡ª Anabstractclass,ontheotherhand,canhaveeitherorboth abstract and non-abstract methods
public abstract void eat();
7
Abstract Method
¡ª Markamethodasabstractwhenyoucannotcomeupwithany generic code that subclasses would find useful (e.g., makeNoise() and e a t ( ) in Animal class)
¡ª Abstractmethodsareimportantinthesensethattheydefine part of the protocol for a group of subtypes (subclasses) used in polymorphism
¡ª Aconcreteclassintheinheritancetreemustimplementallthe abstract methods from its superclass
¡ª Anabstractclass,ontheotherhand,mayimplementnoneor some of the abstract methods from its superclass, leaving the rest to its subclasses to complete the implementation
¡ª Implementinganabstractmethodinasubclassisjustlike overriding a method
8
¡ª Example
Abstract Method
Animal
food hunger location
makeNoise( ) eat() sleep() roam()
¡ª SupposemakeNoise(),eat()androam()are abstract methods in the abstract class Animal
¡ª CanineextendsAnimal
¡ª SinceCanineisalsoanabstractclass,it can choose to implement either none, some or all of the abstract methods from Animal
¡ª Canineonlyimplementstheroam()method from Animal
¡ª DogextendsCanine
¡ª SinceDogisaconcreteclass,itmust therefore implement all the abstract methods from Canine, including those Canine inherited from Animal (i.e., makeNoise() and eat())
C
a
Ca
ne
ni
n
in
e
roam()
D
D
g
o
o
g
makeNoise( ) eat()
9
Pet Shop Program
¡ª Oceanwasaskedtodesignapetshopprogram
¡ª HewouldliketomodifytheAnimalinheritancetreehe designed previously and introduce some pet behaviors such as beFriendly() and play()
¡ª Hecameupwithafewoptions
1. PutthepetmethodsintheAnimalclass
2. PutthepetmethodsintheAnimalclassandmakethem abstract
3. Putthepetmethodsonlyintheclasseswheretheybelong (e.g., in Dog class and Cat class)
10
Pet Shop Program: Option 1
¡ª Pros:
¡ª Allanimalsubclasseswillinstantlyinheritthepetbehaviors
¡ª Noneedtotouchtheexistinganimalsubclasses
¡ª Anyfutureanimalsubclasseswillalsogettotakeadvantage of inheriting these methods
¡ª TheAnimalclasscanbeusedasapolymorphictypeinany program that wants to treat animals as pets
¡ª Cons:
¡ª Notallanimalscanbekeptaspets(Couldbedangerousto
give non-pet animals the pet methods!)
¡ª AlmostcertainlywillhavetotouchthepetclasseslikeDog and Cat because they tend to implement pet behaviors very differently
11
Pet Shop Program: Option 2
¡ª Pros:
¡ª GiveusallthebenefitsofOption1,butwithoutthe drawback of having non-pet animals running around with pet behaviors
¡ª Allsubclassesmustimplementthepetmethods,butthe non-pet classes can make these methods do nothing
¡ª Cons:
¡ª Awasteoftimetoimplementallthepetmethodsinthe
non-pet classes
¡ª Everynon-petclasswouldstillannouncetotheworldthatit, too, has the pet methods, even though these methods wouldn¡¯t actually do anything when being called
12
Pet Shop Program: Option 3
¡ª Pros:
¡ª Thepetmethodsarewheretheybelong,andONLYwhere
they belong
¡ª Cons:
¡ª Thereisnocontractforthepetclasses
¡ª Thecompilerhasnowaytocheckifyouhaveimplemented the methods correctly
¡ª Cannotexploitpolymorphismforthepetmethods
13
Pet Shop Program
¡ª Whatwereallyneedis
¡ª Awaytohavepetbehaviorsinjustthepetclasses
¡ª Awaytoguaranteethatallpetclasseshaveallofthesame pet methods defined
¡ª Awaytotakeadvantageofpolymorphismsothatallpets can have their pet methods called, without having to use specific arguments, return types, and arrays for each and every pet class
How about making a new abstract superclass called Pet, giving it all the pet methods, and making Dog and Cat also a subclass of Pet?
14
Deadly Diamond of Death
¡ª The¡°twosuperclasses¡±approachis called multiple inheritance
¡ª Ithasaproblemknownasthe Deadly Diamond of Death (DDD)
DigitalRecorder
int i
burn()
¡ª Example
¡ª CDBurnerandDVDBurnerboth
CDBurner
burn()
DVDBurner
burn()
extend DigitalRecorder
¡ª Imaginethattheinstancevariablei is used by both CDBurner and DVDBurner, with different values
¡ª WhathappensifComboDriveneedto use both values of i?
¡ª Whichburn()methodrunswhenyou call burn() on the ComboDrive?
ComboDrive
15
Interface
¡ª Javadoesnotallowmultipleinheritance
¡ª Javasolvestheproblemofmultipleinheritancethrough
the use of an interface
¡ª AJavainterfaceislikea100%pureabstractclass,with
all methods being abstract
¡ª AJavainterfaceisdefinedusingthekeywordinterface
public interface Pet {
public abstract void beFriendly(); public abstract void play();
}
Interface methods are implicitly public and abstract, so typing in ¡®public¡¯ and ¡®abstract¡¯ is optional
16
Interface
¡ª Withtheinterfacemethodsbeingabstract,aclass ¡®implementing¡¯ the interface must implement all the interface methods
¡ª Atruntime,theJVMwillthereforenotbeconfusedabout which of the 2 inherited versions it is supposed to call
¡ª Aclassimplementsaninterfaceusingthekeyword implements
implement Pet methods
normal overriding methods
public class Dog extends Canine implements Pet { public void beFriendly() { … }
public void play() { … }
public void makeNoise() { … }
public void eat() { … } }
17
Interface
¡ª Aninterfacecanbeusedasapolymorphictype
¡ª Classesthatimplementaninterfacecancomefrom anywhere in the inheritance tree, or even from completely different inheritance trees
¡ª Anobjectcanbetreatedbytheroleitplays,ratherthan bythe class type from which it was instantiated
¡ª Example:Anyobjectthatneedstobeabletosaveitsstatetoafile should implement the Serializable interface
¡ª Betterstill,aclasscanimplementmultipleinterfaces
public class Dog extends Canine implements Pet, Serializable { … }
18
General Design Rules
¡ª Makeaclassthatdoesnotextendanythingwhenyournew class does not pass the IS-A test for any other type
¡ª Makeasubclassonlywhenyouneedtomakeamorespecific version of a class and need to override or add new behaviors
¡ª Useanabstractclasswhenyouwanttodefineatemplatefora group of subclasses, and you have at least some implementation code that all subclasses could use
¡ª Makeaclassabstractwhenyouwanttoguaranteenobodycan make objects of that type
¡ª Useaninterfacewhenyouwanttodefinearolethatother classes can play, regardless of where these classes are in the inheritance trees
19
Chapter 7.
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
20