polymorphism · • polymorphism – ... • question: how will the java compiler & runtime...
TRANSCRIPT
Polymorphism
Ric Glassey [email protected]
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
POLYMORPHISM
3
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
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
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
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
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
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
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
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
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
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
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( ); }
}
DESIGNING WITH OBJECTS
15
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
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
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(); }
}
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) {...}
}
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
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