21
Polymorphism Ric Glassey [email protected]

Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Polymorphism

Ric Glassey [email protected]

Page 2: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Outline

•  Survey Review (n=18) •  Polymorphism –  Aim: Determine how static and dynamic types

are resolved for method lookup –  Method behaviour within inheritance hierarchies

•  Polymorphic methods •  Overriding default behaviour

•  Designing with objects –  Aim: Explain difference between inheritance and

association (composition and aggregation)

2

Page 3: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

POLYMORPHISM

3

Page 4: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Previously...

•  Review: polymorphic variables in Java –  They can hold variables of different types*

•  Specifically, the declared type, or subtype of the declared type

4

for  (Post  post  :  posts)  {          //  does  not  matter  if  the  post  type  is  MessagePost            //  or  PhotoPost  as  they  are  subtypes  of  Post  and            //  have  the  same  interface          post.display();  }  

: NewsFeed

posts

: MessagePost : PhotoPost : MessagePost

: ArrayList<Post>

addPostshowPosts

posts

NewsFeed

getText

message

MessagePost

getImageFilegetCaption

filenamecaption

PhotoPost

likeunlikeaddCommentgetTimeStampdisplay

usernametimestamplikescomments

Post

Page 5: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

A problem remains

•  Think carefully about the display( ) method declared in class Post, and what it knows about the contents of MessagePost and PhotoPost

5

public  class  Post  {    ...    public  void  display()  {      System.out.println(username);      System.out.println(timestamp);      System.out.println(likes);      for  (String  comment  :  comments)  {        System.out.println(comment);      }      //...what  more  can  be  done??    }  

}   getText

message

MessagePost

getImageFilegetCaption

filenamecaption

PhotoPost

likeunlikeaddCommentgetTimeStampdisplay

usernametimestamplikescomments

Post

Page 6: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Solution #1: Make display( ) class specific

•  Accept that we got too carried away by the power of inheritance to increase flexibility, code reuse and reduce code duplication

•  Compromise: –  Remove display( ) from Post –  Each subclass (MessagePost & PhotoPost) defines

its own display( ) method –  Success?

6

Page 7: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Solution #2: Overriding display( )

•  Each class (super and sub class) defines their own method called display( )

•  All versions have the same method signature –  This is method name + parameters (but the return type is

not important (in Java at least)) •  Each version specifies its own implementation

behaviour depending on which class –  MessagePost will call getText( ) –  PhotoPost will call getImageFile( ) & getCaption( )

•  Question: How will the Java Compiler & Runtime know which version of display( ) to call?

7

Page 8: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Static and Dynamic Types

•  During compilation, type checking uses the static type, but at runtime, dynamic type is used to determine which method should be called

•  A process called method lookup is used to determine the correct method to call

•  Consider three scenarios: –  Object with no inheritance relationship –  Object with a superclass containing target method –  Object with a superclass, and object’s class

overrides the same method in the superclass

8

Page 9: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Scenario #1: No inheritance

•  v1 is an instance of class SimplePost •  SimplePost has no superclass •  v1.display( ); is invoked •  Method lookup occurs as follows

9

: SimplePost

SimplePost v1;

...display( )

...

SimplePost

instanceof

lookup reference

Page 10: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Scenario #2: Inheritance

•  v1 is an instance of class PhotoPost •  PhotoPost has superclass Post •  PhotoPost inherits display( ) •  v1.display( ); is invoked

10

: PhotoPost

PhotoPost v1;

...

...

PhotoPost

instanceoflookup

reference

...display( )

...

Post

inherits from

Page 11: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Scenario #3: Overriding / Polymorphic Method

•  v1 is an instance of class PhotoPost •  v1 is also stored and accessed by type Post

(variable polymorphism) •  PhotoPost overrides display( ) •  v1.display( ) is invoked

11

: PhotoPost

Post v1;

display( )

...

PhotoPost

instanceoflookup

reference

...display( )

...

Post

inherits from

not called, but importantlystops compilation error

Page 12: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Scenario #3: Implications

•  v1 had a static type Post declared in the source code and type checked by the compiler –  Post has a display( ) method, so no syntax errors detected

at compilation •  During runtime, v1 has dynamic type PhotoPost

–  PhotoPost overrides Post’s display( ) method –  By order of precedence, the subclass version of display( )

is executed instead of the Post version •  It leaves one dilemma: Post’s display( ) method

took care of common fields like username, timestamp...do we really have to repeat this code in the subclass versions of display( )?

12

Page 13: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Solution: super.xxx(yyy);

•  As with class constructors in an inheritance hierarchy, we can use super to call any method from the super class, with rules: –  Must explicitly state method name (and any

paramaters that are to be passed) •  e.g. super.display( );

–  Can be used anywhere in the method (not just at the start like super( );)

–  There is no automatic insertion of super.xxx(yyy); by the Java Compiler

13

Page 14: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Solution: super.display( );

14

public  class  Post  {    ...    public  void  display(  )  {      System.out.println(username);      System.out.println(timestamp);      System.out.println(likes);      for  (String  comment  :  comments)  {        System.out.println(comment);      }    }  

}  

public  class  PhotoPost  extends  Post{    ...    public  void  display()  {      System.out.println(getImageFile);      System.out.println(getCaption);      super.display(  );    }  

}  

Page 15: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

DESIGNING WITH OBJECTS

15

Page 16: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Thinking in objects

•  Designing systems with objects demands that we can both: –  Choose appropriate entities to model as objects

•  Encapsulate related information fields and methods •  Selectively expose object information to other objects

–  Information Hiding –  Access levels (private, protected, public)

–  Form meaningful relationships between objects •  Inheritance (“...Is a...”) between classes •  Composition (“...Has a...” association) of objects •  Aggregation (weak “...Has a...” association) of objects

16

Page 17: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Inheritance

•  Applied when specialism is required and code reuse is possible

•  “...is a...” relationship •  For example, a Car is

a more specialised type of Vehicle

17

Car

Vehicle

Page 18: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Composition •  Objects can be combined

to form more complex concepts

•  “...has a...” relationship •  Car has a Gearbox, and has

an Engine •  If car is destroyed, so too

are gearbox and engine

18

Car

Engine

Gearbox

public  class  Car  {    Gearbox  gbx;    Engine  eng;        public  Car()  {      gbx  =  new  GearBox();      eng  =  new  Engine();    }  

}  

Page 19: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Aggregation •  A type of association,

except objects may be created externally from the containing object

•  “...Contains...” or weak “...has a...”relationship

•  For example, if a University has a Department that has many Students and Staff

19

University

Department Staff Students

Person

public  class  Department  {    ArrayList<Staff>  staff;    ArrayList<Student>  students;        public  Department()  {      ...      students  =  new  ArrayList<Student>();    }  

   public  void  addStudent  (Student  s)  {...}  

}  

Page 20: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Office Design Challenges

•  Which strategy would you use for modelling: –  The types of rooms in a floor of an office? –  The available rooms in an floor of an office? –  The floors within an office? –  The staff members working on a particular floor? –  The relationships between staff members? –  The stationary cupboard?

20

Page 21: Polymorphism · • Polymorphism – ... • Question: How will the Java Compiler & Runtime know which version of display( ) to call? 7 . Static and Dynamic Types • During compilation,

Readings

•  Chapter 9, Objects First with Java **required**

•  Useful guidance if you want to get better at expressing OOP software visually using UML: –  UML Basics: The Class Diagram

•  http://www.ibm.com/developerworks/rational/library/content/RationalEdge/sep04/bell/

–  UML2 Class Diagrams: An Agile Introduction •  http://agilemodeling.com/artifacts/classDiagram.htm

•  Interesting retrospective from Ivar Jacobson (contributor to UML and alumni of KTH) –  http://www.infoq.com/interviews/Ivar_Jacobson

21