Post on 02-Jun-2018
8/11/2019 Inheritance Polymorph is m
1/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
MIN 545 - Lecture IVInheritance and Polymorphism
c2012 Aybar C. Acar
Rev. 1.1 (Build 20130327132700)
MIN 545 - Inheritance & Polymorphism 1of54
8/11/2019 Inheritance Polymorph is m
2/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
A Puzzle...
All HourlyEmployees are also Employees.
Some Employees are Salaried.Executives are always Salaried.HourlyEmployeesare never Salaried.Technical staff areSalaried employees that are not Executives.Some Hourly employees are Part-time.Technical staff
are eitherEngineers
,Technicians
orClerks
.Full-time hourly employees are Hourly Employees but not Part-time.
Employee
HourlyEmployee SalariedEmployee
TechnicalFullTime ExecutivePartTime
Engineer Technician Clerical
MIN 545 - Inheritance & Polymorphism 2of54
8/11/2019 Inheritance Polymorph is m
3/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Inheritance
Class Inheritanceallows us to:
Create simple parent objects and to make them morespecialized.
Have specializations share the variables & methods of theircommon ancestors.
Write the code once, and re-use in many children! (Laziness)MIN 545 - Inheritance & Polymorphism 3of54
8/11/2019 Inheritance Polymorph is m
4/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Deriving Classes in Java
Derived class,subclass,child classall mean the same thing.
Base class,superclass,parent classall mean the same thing.
Base Class:
p u bl i c c la s s E m pl o ye e
{
p r ot e ct e d S t ri n g n am e ;
p r ot e ct e d l on g i d Nu m be r ;
}
Child (derived class):
p u bl i c c la s s H o u rl y E mp l o ye e e x te n ds E m pl o ye e
{
p r iv a te f l oa t h o ur l y Ra t e ;p r iv a te i nt h o u rs W o rk e d ;
}
The HourlyEmployee objects have name and idNumber inherited from
Employee, but they also include new variables: hourlyRate and
hoursWorked.MIN 545 - Inheritance & Polymorphism 4of54
8/11/2019 Inheritance Polymorph is m
5/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Inheritance in UML
+ makeSound(): void+ eat(): void
# age : int- sound : String
Animal
+flyTo(Location):void+layEggs(): Egg[]
# airSpeed : int# eggSize: float
Bird
+sleep(int): void+giveBirth(): Mammal[]
# numTeeth : int
# hasFur: boolean
Mammal
In UML, inheritance relationships are shown with an arrow with aclosed, white arrowhead
The arrow is from the child to the parent and is called an Is-Arelationship
e.g. Bird is an Animal
Notice that the variables/methods inherited are not re-shown in thechild diagrams.
MIN 545 - Inheritance & Polymorphism 5of54
I h i Vi ibili O id P l hi Ab Cl I f
8/11/2019 Inheritance Polymorph is m
6/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Structure of a Derived Class
this super
Employee
HourlyEmployee
55.45
765
float hourlyRate
int hoursWorked3482942932
"Mehmet Sarcizmeli"
int idNumber
String name
Every child class is its
own type and also ofits parents type(s).
Creation of a derivedobject involves thecreation of its parent
as well.The child holds itsparents spec withinitself.
e.g. you have yourparents DNA.
Each derived objectrefers to its parentversion using the
reference superMIN 545 - Inheritance & Polymorphism 6of54
I h i Vi ibili O id P l hi Ab Cl I f
8/11/2019 Inheritance Polymorph is m
7/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Visibility in Inheritance
Remember the three classes of visibility, in order of permissiveness:
public : Public variables and methods are accessible byeveryone.
protected : Protected variables and methods are only accessible
by the class and its derived classes.
private : Private variables and methods are accessible only bythe class itself.
super and this are alwaysprivate.
super is even more restrictive than private as itcannot be returned in a method or assigned toanother reference. It can only be used directly.
MIN 545 - Inheritance & Polymorphism 7of54
I h it Vi ibilit O id P l m hi m Ab t t Cl I t f
8/11/2019 Inheritance Polymorph is m
8/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Exercise
Assume the following case:
class A {p ri va te i nt v A1 ;
p r ot e ct e d f lo a t v A2 ;
p ub li c S tr in g v A3 ;
p ub li c v oi d f A1 ( ) { S ys te m . o ut . p r in tl n ( v A1 ) };
p ro te ct ed int fA2 ( int m ) { r etu rn m * ( int ) vA2 };
p ri va te b oo le an fA 3 () { r et ur n ( vA 1 < vA 2) };
}
cla ss B e xt end s A {
pr iv at e int vB1 = 3;
p ub li c f lo at v B2 ;
}
class C {
p ri va te A vC 1 ;
p ri va te B vC 2 ;
}
MIN 545 - Inheritance & Polymorphism 8of54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
9/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Exercise
+ fA1() : void# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C Example
Can we add the following methodto the definition of class C?
p ub li c f lo at f C4 ( )
{
r e tu r n v C1 . v A 2 ;
}
NO. Class C is not a child of
class A. Therefore it cannotaccess protected variables.
MIN 545 - Inheritance & Polymorphism 9of54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
10/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Exercise
+ fA1() : void
# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C
Example
Can we add the following methodto the definition of class B?
p u bl i c S t ri n g f B1 ( ){
r e tu r n v A3 ;
}
YES. vA3 is an instance variable
of B inherited from parent classA. It is public so everyone canaccess it.
MIN 545 - Inheritance & Polymorphism 10 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
11/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Exercise
+ fA1() : void
# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C
Example
Can we add the following methodto the definition of class B?
p ub li c f lo at f B2 ( ){
r e tu r n v A2 ;
}
YES. vA2 is an instance variable
of B inherited from parent classA. It is protected and B is a childof A, so B can access it.
MIN 545 - Inheritance & Polymorphism 11 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
12/54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Exercise
+ fA1() : void
# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C
Example
Can we add the following methodto the definition of class B?
p ub li c i nt f B3 ( ){
r e tu r n v A1 ;
}
NO.vA1 is an instance variable of
B inherited from parent class A.But, it is private and even if B isa child of A, B can not access it.
MIN 545 - Inheritance & Polymorphism 12 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
13/54
y y p
Exercise
+ fA1() : void
# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C
Example
Can we add the following methodto the definition of class C?
p ub li c v oi d f C4 ( ){
v C 2 . f A 1 ( ) ;
}
YES. fA1 is a method of B
inherited from parent class A. Itis publicso it can be accessed byobjects of class C.
MIN 545 - Inheritance & Polymorphism 13 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
14/54
Exercise
+ fA1() : void
# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C
Example
Can we add the following methodto the definition of class C?
p ub li c i nt f C5 ( i nt a ){
r e tu r n v C2 . f A 2 ( a );
}
NO.fA2 is a protected method
of B inherited from parent classA. Since C is not a child of A, itcannot access fA2.
MIN 545 - Inheritance & Polymorphism 14 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
15/54
Exercise
+ fA1() : void
# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C
Example
Can we add the following methodto the definition of class B?
p ub li c i nt f B4 ( i nt a ){
r e tu r n f A2 ( a ) ;
}
YES. fA2 is a protectedmethod
of B inherited from parent classA. Since B is a child of A, it canaccess fA2.
MIN 545 - Inheritance & Polymorphism 15 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
16/54
Exercise
+ fA1() : void# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C Example
Can we add the following methodto the definition of class B?
p u bl i c b o ol e an f B5 ( )
{
r e tu r n f A3 ( ) ;
}
NO.fA3 is a private method of
A. Although B is a child of A, itcan notaccess fA3.
MIN 545 - Inheritance & Polymorphism 16 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
17/54
Exercise
+ fA1() : void
# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C
ExampleCan we add the following methodto the definition of class B?
p ub li c B f B6 ( )
{
r e tu r n t hi s ;}
YES. this is a private variableof B. B can access and return itsown address.However, this is sort of useless...If you can call fB6() on someobject, it means you already haveits reference!
MIN 545 - Inheritance & Polymorphism 17 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
18/54
Exercise
+ fA1() : void
# fA2(int) : int- fA3() : bool
- vA1 : int# vA2 : float+ vA3 : String
A
- vB1 : int+ vB2 : float
B
- vC1 : A- vC2 : B
C
Example
Can we add the following methodto the definition of class B?
p ub li c A f B6 ( )
{r e tu r n s u pe r ;
}
NO. super is a private variableof B and normally this would be
fine. But super is an exceptionalcase in that B can use super butcan never give it away.
MIN 545 - Inheritance & Polymorphism 18 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
19/54
Overriding Methods
A method is uniquely defined by its nameandparameter list.
This is called the methodssignature(or fingerprint)
A class can define two methods with the same name butdifferent parameters.
Remember, this is calledoverloading
Java will not allow two different methods with the samesignature in the same class.
However a child class can define a new method with the samesignature as that of its parent class.
Assume class A has:
p ub li c v oi d f A1 ( ) { S ys te m . ou t . p ri nt ln ( v A1 ) ; }
Child class B can define:
p ub li c v oi d f A1 ( ) { S ys te m . ou t . p ri nt ln ( v A2 * 2 ); }
This is calledoverriding.
MIN 545 - Inheritance & Polymorphism 19 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
20/54
Example
p ub li c c la ss P er so n {
p r ot e ct e d S t ri n g n am e ;
p u bl i c v oi d g e tN a me ( )
{
r e tu r n n am e ;
}
}
p ub li c c la ss D oc to r e xt en ds P er so n {
@Override
p u bl i c v oi d g e tN a me ( )
{
r et ur n " D r . " + n am e ;
}
}
Theoverride annotation(@Override) is optional but recommended
The compiler will warn you if your override is not OK
(misspelled name &c).MIN 545 - Inheritance & Polymorphism 20 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
21/54
Object: The Mother of All Classes
Java has a predefined class named Object
Every class in Java is a child of the Object class
Even if a class does not extend another class, it is assumed toextend Object.
Two important methods provided by Object:public String toString()Gives a string representation of the object.
System.out.printXXfamily of functions use this if given an
arbitrary object to print.
The default is to a string of the form
< Classname> @ < Address>
public boolean equals(Object other)
The default is to check whether they have the same address.
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.htmlMIN 545 - Inheritance & Polymorphism 21 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.htmlhttp://docs.oracle.com/javase/7/docs/api/java/lang/Object.html8/11/2019 Inheritance Polymorph is m
22/54
Using superfor Overrides
If a method is overridden by the child class, you can use super
to access the parent version.
Example
p ub li c c la ss P er so n {
p r ot e ct e d S t ri n g n am e ;
p u bl i c v oi d g e tN a me ( ){
r e tu r n n am e ;
}
}
p ub li c c la ss D oc to r e xt en ds P er so n {
@Override
p u bl i c v oi d g e tN a me ( )
{
r et ur n " D r . " + s up er . g e t Na me ( ) ;
}
}
MIN 545 - Inheritance & Polymorphism 22 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
23/54
superin Constructors
The construction of every object requires construction of the parent
object as well.This is usually done automatically by Java, if the parent has adefault constructorWhat if it doesnt?
The child must define a constructor and call the parentconstructor explicitly.
Example
p ub li c c la ss P er so n {
p r ot e ct e d S t ri n g n am e ;
p ub li c P er so n ( St ri ng n am e ) { t hi s . na me = n am e ; }
}p ub li c c la ss D oc to r e xt en ds P er so n {
p ub li c D oc to r ( S tr in g n am e ) { s up er ( n a me ) ; }
}
Like this, super must be the first thing called in a constructor!MIN 545 - Inheritance & Polymorphism 23 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
24/54
Case Study: Aircraft
Aircraft
Helicopter Airplane Airport
Airliner MilitaryPlane
B747 F16
Airbase
MIN 545 - Inheritance & Polymorphism 24 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
25/54
Case Study: Aircraft Class
p ub li c c la ss A ir cr af t {
// E ve ry c ra ft h as a u ni qu e r eg is tr at io n ID ( e. g. TC - A CA )
p ub li c s ta ti c f in al i nt M AX _A LT = 5 00 00 ;
p r iv a te S t ri n g r e gI D ;
p r ot e ct e d i nt a l ti t ud e ;
p ub li c A ir cr af t ( St ri ng id ) { r eg ID = id ; }
p ub li c S tr in g g et Re gI D () { r et ur n r eg ID ; }
p ub li c i nt g et A lt it u de ( ) { r et ur n a lt it ud e ; }
p ub li c v oi d s en d Ra di o Ms g ( S t ri ng m sg ) {
S ys te m . ou t . p ri nt f ( " %s t o B as e : % s %n " , r eg ID , m sg ) ;
}
p ub li c b oo le an t ak eO ff ( i nt a lt ) {
if ( alt > MA X_ AL T ) {s en dR ad io Ms g (" Can t go to " + alt + " m ." );
r e tu r n f a ls e ;
}
s e n d R a d io M s g ( " T a k i ng o f f ! " ) ;
a lt it ud e = a lt ;
r e tu r n t ru e ;
}}MIN 545 - Inheritance & Polymorphism 25 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
26/54
Case Study: Helicopter Class
p u bl i c c la s s H e l ic o p te r e x te n ds A i rc r af t
{
p u bl i c H e li c o pt e r ( S t r in g r eg I D )
{
s u p e r ( r e g I D ) ;
}
p ub li c b oo le an t ak eO ff ( i nt a lt )
{
S y s t em . o u t . p r i n t l n ( " S t a r t i n g r o t o r . . . " ) ;
r e t u rn s u p er . t a k e Of f ( a l t ) ;
}
}
MIN 545 - Inheritance & Polymorphism 26 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
27/54
Late Binding
Consider the following method invocation:
obj.doIt();
At some point, this invocation is bound to the definition of themethod that it invokes:
At compile time,At initial run,During runtime.
If this binding occurred at compile time, then that line of codewould call the same method every time
However, Java defers method binding until run time this iscalleddynamic bindingorlate binding
MIN 545 - Inheritance & Polymorphism 27 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
28/54
Polymorphism
Polymorphism: having many forms
Apolymorphic referenceis a reference that may refer todifferent objects.
e.g. Every object in Java is of type Object.
Object o may refer to any object of the class Object.
The method invoked through a polymorphic reference canchange from one invocation to the next.
All object references in Java are potentially polymorphic.
Any object can be refered to as its own type or any of itsparent types.Java decides which method to invokeat the last possible step.
MIN 545 - Inheritance & Polymorphism 28 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
29/54
Example
P er so n p1 = n ew P er so n ( " Al i " );P er so n p2 = n ew D oc to r ( " Ba nu " ) ;
S y s t e m . o u t . p r i n t l n ( p 1 . g e t N a m e ( ) ) ;
S y s t e m . o u t . p r i n t l n ( p 2 . g e t N a m e ( ) ) ;
Output:
AliDr. Banu
From Javas perspective, at first, both p1and p2are Person
objects.When getName() needs to be invoked, Java binds theinvocation.
Realizes at that point that p2 is a Doctor
MIN 545 - Inheritance & Polymorphism 29 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
30/54
The instanceofoperator
Type membership can be checked using the instanceof
operator.Expression format:
< object reference> instanceof < class name>
Returns true if the object belongs to the class, false if not.
Example
P er so n p1 = n ew P er so n ( " Al i " );
P er so n p2 = n ew D oc to r ( " Ba nu " ) ;
p 1 i ns t an ce of P er so n ; / / r e tu r ns t ru e ;p 2 i ns t an ce of P er so n ; / / r e tu r ns t ru e ;
p 1 i ns t an ce of D oc to r ; / / r e tu r ns f a ls e ;
p 2 i ns t an ce of D oc to r ; / / r e tu r ns t ru e ;
p 1 i ns t an ce of O bj ec t ; / / r e tu r ns t ru e ;
p 2 i ns t an ce of S tr in g ; / / r e tu r ns f a ls e ;
MIN 545 - Inheritance & Polymorphism 30 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
31/54
Case Study: Airport Class
p u bl i c c la s s A i rp o rt
{
p r iv a te i nt r u n wa y L en g t h ;p r iv a te S t ri n g c od e ;
p ub li c A ir po rt ( i nt r wL en , S tr in g c od e )
{
r un w ay L en g th = r wL en ;
t hi s . c od e = c od e ;}
p u bl i c i nt g e t Ru n w ay L e ng t h ( )
{
r e tu r n r u n wa y L en g t h ;
}
p u bl i c b o ol e an g e t Pe r m is s i on ( A i rc r af t a )
{
i f ( a i n st an c eo f M i li t ar y Pl an e )
r e tu r n f a ls e ;
r e tu r n t ru e ;
}
}MIN 545 - Inheritance & Polymorphism 31 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
8/11/2019 Inheritance Polymorph is m
32/54
Case Study: Airplane Class
p u bl i c c la s s A i rp l an e e x te n ds A i rc r af t
{
p r iv a te i nt m i nR u nw a y ;
p r iv a te A i rp o rt m y Ai r p or t ;
p ub li c A ir pl an e ( S tr in g r eg ID , i nt m in Ru nw ay )
{
s u p e r ( r e g I D ) ;
t hi s . m i n R un w ay = m i nR u nw a y ;
}
p u bl i c v oi d s e tA i r po r t ( A i r po r t a )
{ m yAirport = a ;
}
MIN 545 - Inheritance & Polymorphism 32 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
C S d A l Cl ( )
8/11/2019 Inheritance Polymorph is m
33/54
Case Study: Airplane Class (cont.)
p ub li c b oo le an t ak eO ff ( i nt a lt )
{ if ( m yA ir po rt == n ul l ) {
s e n d R a d i oM s g ( " N o a i r p or t ! " ) ;
r e tu r n f a ls e ;
}
s e n d R a d io M s g ( " S t a r t in g e n g i ne . " ) ;
s e n dR a d io M s g ( " M o vi n g t o r u nw a y . " );
i f ( ! m y A ir p or t . g e t P e r mi s s io n ( t h i s ) ) {
s e n dR a d io M s g ( " No p e rm i s si o n t o t ak e - o f f ! " ) ;
r e tu r n f a ls e ;
}
i f ( m y Ai rp o rt . g e t R un w ay L en g th ( ) < m in R un wa y ) {s e n dR a d io M s g ( " R u nw a y t oo s h or t ! " ) ;
r e tu r n f a ls e ;
}
r e t u rn s u p er . t a k e Of f ( a l t ) ;
}}
MIN 545 - Inheritance & Polymorphism 33 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
C S d Mili Pl Cl
8/11/2019 Inheritance Polymorph is m
34/54
Case Study: MilitaryPlane Class
p u bl i c c la s s M i l it a r yP l a ne e x te n ds A i rp l an e
{
p ub li c M i li t ar y Pl an e ( S t ri ng r eg ID , i nt r l )
{
s u pe r ( r eg ID , r l );
}
}
MIN 545 - Inheritance & Polymorphism 34 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
C S d Ai li Cl
8/11/2019 Inheritance Polymorph is m
35/54
Case Study: Airliner Class
p u bl i c c la s s A i rl i ne r e x te n ds A i rp l an e
{p ub li c A ir li ne r ( S tr in g id , S tr in g M od el , i nt rl )
{
su per ( Mod el + " -" + id , rl );
}
p ub li c b oo le an t ak eO ff ( i nt a lt )
{s e n dR a d io M s g ( " T u r ni n g o n s e at b el t s ig n . " ) ;
i f ( s u pe r . t a k e Of f ( a l t ) )
{
s e n dR a d io M s g ( " T u rn i ng o ff s e at b el t s ig n . " ) ;
r e tu r n t ru e ;
}
else
r e tu r n f a ls e ;
}
}
MIN 545 - Inheritance & Polymorphism 35 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
C St d B 747
8/11/2019 Inheritance Polymorph is m
36/54
Case Study: B-747
p ub li c c la ss B 74 7 e xt en ds A ir li ne r
{
p u bl i c B 74 7 ( S t r in g i d )
{
s u pe r ( id , " B 7 47 " , 2 0 00 ) ;
}
p ub li c b oo le an t ak eO ff ( i nt a lt )
{
r e t u rn s u p er . t a k e Of f ( a l t ) ;
}
}
MIN 545 - Inheritance & Polymorphism 36 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
C St d F 16
8/11/2019 Inheritance Polymorph is m
37/54
Case Study: F-16
p ub li c c la ss F 16 e xt en ds M i li t ar y Pl an e
{
p ub li c F 16 ( S t ri ng i d)
{
s up er ( " F16 - " + id , 1 00 0) ;
}
p ub li c b oo le an t ak eO ff ( i nt a lt )
{
r e t u rn s u p er . t a k e Of f ( a l t ) ;
}
}
MIN 545 - Inheritance & Polymorphism 37 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
M ltiple Inheritance
8/11/2019 Inheritance Polymorph is m
38/54
Multiple Inheritance
Sometimes an class will naturally be a subclass of two different
classes.Example
The V-22 Osprey, flies like a plane, lands like a helicopter.
Airplane Helicopter
Osprey
Some programming languages allow this.Multiple Inheritance
In Java, multiple inheritance is not allowed.A class is allowed to extend only one class.Why?
MIN 545 - Inheritance & Polymorphism 38 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
The Problem with Multiple Inheritance
8/11/2019 Inheritance Polymorph is m
39/54
The Problem with Multiple Inheritance
+ land()
Aircraft
+ land()Airplane
+ land()Helicopter
Osprey
land() ?
Assume that the following:Aircraft class has a method called land(), so all its childrenmust have it.
Airplane and Helicopter have their own overrides ofland()
Osprey has no implementation ofland()
What happens when someone invokes land() on an Ospreyobject?
MIN 545 - Inheritance & Polymorphism 39 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
The Diamond Problem
8/11/2019 Inheritance Polymorph is m
40/54
The Diamond Problem
+ land()
Aircraft
+ land()Airplane
+ land()Helicopter
Osprey
land() ?
This is called theDiamond ProblemThe Deadly Diamond of Death
It is the major reason why some programming languages
eschew multiple inheritance.In Java, the diamond problem would be very common.
All classes descend from Object.The Object methods (e.g. toString()) would frequentlycause problems.
MIN 545 - Inheritance & Polymorphism 40 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Abstract Methods and Classes
8/11/2019 Inheritance Polymorph is m
41/54
Abstract Methods and Classes
Anabstract methodis a method prototype without the
implementation.It is the promiseof a method.
They are declared just like normal methods but with thekeyword abstract and no body. e.g.
p ub li c a bs tr ac t v oi d f oo ( i nt x );
Classes that declare abstract methods cannot be instantiated.
What if somebody actually calls the abstract method?These are calledAbstract Classes
The child of an abstract classmust
override the abstractmethod or also be abstract itself.
Abstract classes are declared using the abstract keyword.
p ub li c a bs tr ac t c la ss H ed e { .. . }
MIN 545 - Inheritance & Polymorphism 41 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Motivating Problem
8/11/2019 Inheritance Polymorph is m
42/54
Motivating Problem
Lets say you create the following design:
Ellipse Rectangle Triangle
+ Shape(double,double)+ getWidth() : double+ getHeight() : double
+ getArea() : double
- double width- double height
Shape
height
width
The problem is getArea()
How do you calculate the area of an undefined shape?If only we could leave it for later...
MIN 545 - Inheritance & Polymorphism 42 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Solution: Abstract Parent Class
8/11/2019 Inheritance Polymorph is m
43/54
Solution: Abstract Parent Class
Make shape abstractThe child classes will have to deal with calculating the area.
p ub li c a bs tr ac t S ha pe {
p r iv a te d o ub l e w i dt h ;
p r iv a te d o ub l e h e ig h t ;
p ub li c S ha pe ( d o ub le w , d ou bl e h )
{ width = w ; height = h ; }
p ub li c d ou bl e g et Wi dt h ( ) { r e tu rn w id th ; }
p ub li c d ou bl e g et He ig h t () { r e tu rn h ei gh t ; }
/ * T he i m pl em e nt a ti o n of g et Ar ea is l ef t to c hi ld c la ss es */
p u bl i c a b st r ac t d o ub l e g e tA r ea ( ) ;
}
MIN 545 - Inheritance & Polymorphism 43 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Solution (cont ): Child Classes
8/11/2019 Inheritance Polymorph is m
44/54
Solution (cont.): Child Classes
p ub li c c la ss R ec t an gl e {
p ub li c R ec ta ng le ( d ou bl e w , d ou bl e h ) { s up er ( w ,h ); }p ub li c d ou bl e g et Ar ea ( ) {
r et ur n g et Wi dt h ( ) * g et H ei gh t ( );
}
}
p ub li c c la ss T ri an gl e {
p ub li c T ri an gl e ( d ou bl e w , d ou bl e h ) { s up er ( w ,h ); }p ub li c d ou bl e g et Ar ea ( ) {
r et ur n 0 .5 * g et Wi dt h ( ) * g et He i gh t ( );
}
}
p ub li c c la ss E ll ip se {
p ub li c E ll ip se ( d ou bl e w , d ou bl e h ) { s up er ( w ,h ); }
p ub li c d ou bl e g et Ar ea ( ) {
r et ur n 0 .2 5 * M at h . PI * g et Wi dt h () * g et He ig ht ( );
}
}
MIN 545 - Inheritance & Polymorphism 44 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Rules of the Game
8/11/2019 Inheritance Polymorph is m
45/54
Rules of the Game
You cannot instantiate an abstract class even if it has a
constructor and no abstract methodse.g. Foo f = new Foo() is not allowed if Foo is abstract.Foo is abstract; cannot be instantiated
Concrete (non-abstract) classes cannot declare abstractmethods.
MyClass is not abstract and does not override abstractmethod foo() in MyClass
Concrete classes cannot not override abstract methods of theirparents.
MyChild is not abstract and does not override abstractmethod foo() in MyParent
Abstract methods cannot be private
illegal combination of modifiers: abstract andprivate
MIN 545 - Inheritance & Polymorphism 45 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Interfaces
8/11/2019 Inheritance Polymorph is m
46/54
Interfaces
Interfacesare a special form similar to abstract classes that
embody a property or ability of objects:Cannot be instantiated.Cannot have variables.Can only have public abstractmethods.
They are declared using the interface keyword:
Example
p ub li c i n te rf ac e C ol or fu l {
p u bl i c C o lo r g e tC o lo r ( ) ;
p ub li c v oi d s et Co lo r ( C ol or c ) ;
}
Notice that you do not need to declare individual methodsabstract.It is assumed since all methods of an interface are abstract.
MIN 545 - Inheritance & Polymorphism 46 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Use of Interfaces
8/11/2019 Inheritance Polymorph is m
47/54
Use of Interfaces
Interfaces sometimes embody the adjectives in a requirements
specification.e.g. ...some kinds types fabric will be colorful.Typically interface names end in -ableor-er
e.g. ConnectionHandler, Comparable, Iterator
Classesimplementthe interfaces:
Example
c la ss C o tt o nF a br i c e xt en ds F ab ri c i m pl em en t s C ol or fu l {
C o lo r c o lo r ;
//...
p ub li c C ol or g et Co lo r ( ) { r e tu rn c ol or }
p ub li c v oi d s et Co lo r ( Co lo r c ) { c ol or = c ;}
}
A concrete class that implements an interface must implementall its methods.
MIN 545 - Inheritance & Polymorphism 47 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Interfaces and Multiple Inheritance
8/11/2019 Inheritance Polymorph is m
48/54
p
Since interfaces do not have state or concrete methods, they
do not cause the diamond problem.
Therefore a class can extend one class and implement one ormoreinterfaces
Example
c la s s E m pl o ye e e x te n ds P e rs o n i m pl e m en t s T ax pa ye r , E m pl o y ab l e
c la s s C o mp a ny e x te n ds O r g an i z at i o n i m p le m e nt s T ax pa ye r , E m pl o ye r
c la s s C h ar i ty e x te n ds O r g an i z at i o n i m p le m e nt s E m pl o ye r
c la s s I n te r n e x te n ds P e rs o n i m p le m e nt s E m pl o y ab l e
Therefore Java uses them to simulatemultiple inheritance
Other languages have similar constructs calledMixins
MIN 545 - Inheritance & Polymorphism 48 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Abstract Classes and Interfaces in UML
8/11/2019 Inheritance Polymorph is m
49/54
+ Organization(String)+ getName() : String...
# name : String
Organization
+ Charity(String, String)+ getCause() : String..
# cause : StringCharity
+ Company(String)+ getRevenue() : double..
# revenue : double# numEmployees : int
Company
+ Person(String)+ getName() : String
# name : String# age : int# idnumber : long
Person
+ Employee(String)+ getSalary() : int..
# salary : double# ssn
Employee
+ Intern(String)+ getSchool() : String..
# school : StringIntern
+ getNumEmployees() : int
Employer
+ calculateTax() : double
Taxpayer
+ getIDNumber() : long
Employable
Abstract classes and interfaces are marked above their names.
The implementsrelationships are shown with dashed arrows.
MIN 545 - Inheritance & Polymorphism 49 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Solution to the Osprey Problem
8/11/2019 Inheritance Polymorph is m
50/54
p y
The problem with the Osprey is that it is a plane in allrespects, except it can take off and land like a helicopter.
Helicopters can do Vertical Take Off and Landing (VTOL) onlyAirplanes can do Convential Take-Off and Landing (CTOL)onlyThe Osprey can do both
So if the Osprey becomes the child of Airplane but also hasVTOL, we solve the problem.
We might encapsulate these into two interfaces:
i nt er fa ce V TO L {
p u bl i c v oi d V T ak e Of f ( ) ;
p u bl i c v oi d V L an d ( ) ;
}
i nt er fa ce C TO L {
p u bl i c v oi d T a ke O ff ( ) ;
p ub li c v oi d L an d ( );
}
MIN 545 - Inheritance & Polymorphism 50 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Solution to the Osprey Problem (cont.)
8/11/2019 Inheritance Polymorph is m
51/54
p y ( )
Aircraft
Airplane
Helicopter
Osprey
VTOL
CTOL
The Osprey now inherits its CTOL behaviour from Airplane
It gets the VTOL behviour by implementing VTOL separately.
MIN 545 - Inheritance & Polymorphism 51 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Polymorphism With Interfaces
8/11/2019 Inheritance Polymorph is m
52/54
You can have references to interfaces.Can refer to any object implementing that class.
Hence, interface references are polymorphic:
Example
V TO L v [] = ne w V TO L [2 ];
v [ 0] = n ew H e li co p te r ( );
v [1] = n ew O sp re y () ;
CTOL c = ( CTOL ) v [1];
However, CTOL c = (CTOL) v[0]will cause a ClassCastException since v[0] is a
Helicopterand does not implement CTOL.
When referring to an object through an interface reference,you can only call methods defined by that interface.
MIN 545 - Inheritance & Polymorphism 52 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Interface Hierarchies
8/11/2019 Inheritance Polymorph is m
53/54
Interfaces can inherit from other interfaces, just like classes.
The child interface inherits all the abstract methods of theparent.
A class implementing the child interface must also implementthe parent interface.
Example
p ub li c i n te rf ac e W al ke r {
p ub li c v oi d w al k ( );
}
p ub li c i n te rf ac e R un ne r e xt en ds W al ke r {p ub li c v oi d r un ( );
}
Anything that implements Runner must have both the walk() andrun() methods.
MIN 545 - Inheritance & Polymorphism 53 of 54
Inheritance Visibility Overrides Polymorphism Abstract Classes Interfaces
Summary
8/11/2019 Inheritance Polymorph is m
54/54
Concrete Class Abstract Class Interface
Normal Methods YES YES NOAbstract Methods NO YES YES
Variables YES YES NOStatics YES YES NO
Constants YES YES YESInstantiation YES NO NO
MIN 545 - Inheritance & Polymorphism 54 of 54