25
Engr 691 Engr 691 Special Topics in Special Topics in Engineering Science Engineering Science Software Architecture Software Architecture Spring Semester 2004 Spring Semester 2004 Lecture Notes Lecture Notes

Polymorphism (Budd's UOOPJ, Ch. 12)

  • Upload
    raja

  • View
    31

  • Download
    0

Embed Size (px)

DESCRIPTION

Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes. Polymorphism (Budd's UOOPJ, Ch. 12). This is a set of "slides" to accompany chapter 12 of Timothy Budd's textbook Understanding Object-Oriented Programming with Java, Updated Edition - PowerPoint PPT Presentation

Citation preview

Page 1: Polymorphism  (Budd's UOOPJ, Ch. 12)

Engr 691Engr 691Special Topics in Engineering ScienceSpecial Topics in Engineering Science

Software ArchitectureSoftware Architecture

Spring Semester 2004Spring Semester 2004

Lecture NotesLecture Notes

Page 2: Polymorphism  (Budd's UOOPJ, Ch. 12)

Polymorphism Polymorphism (Budd's UOOPJ, Ch. 12)(Budd's UOOPJ, Ch. 12)

This is a set of "slides" to accompany This is a set of "slides" to accompany chapter 12 of chapter 12 of

Timothy Budd's textbook Timothy Budd's textbook Understanding Object-Oriented Programming with Java, Understanding Object-Oriented Programming with Java,

Updated EditionUpdated Edition (Addison-Wesley, 2000)(Addison-Wesley, 2000)

Page 3: Polymorphism  (Budd's UOOPJ, Ch. 12)

Definition Definition

PolymorphousPolymorphous: : – Having, or assuming, various forms, characters, or Having, or assuming, various forms, characters, or

styles (styles (Webster's Collegiate Dictionary, Fifth EditionWebster's Collegiate Dictionary, Fifth Edition).).

Term used in several different ways in computer Term used in several different ways in computer

science science

Page 4: Polymorphism  (Budd's UOOPJ, Ch. 12)

Polymorphism in Polymorphism in Programming LanguagesProgramming Languages

A variable holding a value drawn from a A variable holding a value drawn from a group of types group of types

A name associated with several different A name associated with several different function bodies function bodies

A single function with polymorphic A single function with polymorphic variables as parameters variables as parameters

Page 5: Polymorphism  (Budd's UOOPJ, Ch. 12)

Polymorphism in Polymorphism in Untyped LanguagesUntyped Languages

Polymorphism is trivial issue in untyped languages Polymorphism is trivial issue in untyped languages

All variables are potentially polymorphic All variables are potentially polymorphic

Variables take on type of their values dynamicallyVariables take on type of their values dynamically silly: x silly: x " a silly Smalltalk polymorphic method " " a silly Smalltalk polymorphic method " (x isKindOf: Integer) ifTrue: [ ^ x + 1 ] . (x isKindOf: Integer) ifTrue: [ ^ x + 1 ] . (x isKindOf: Fraction) ifTrue: [ ^ x reciprocal ]. (x isKindOf: Fraction) ifTrue: [ ^ x reciprocal ]. (x isKindOf: String) ifTrue: [ ^ x reversed ] . (x isKindOf: String) ifTrue: [ ^ x reversed ] . ^ nil ^ nil

Page 6: Polymorphism  (Budd's UOOPJ, Ch. 12)

Forms of PolymorphismForms of Polymorphism

polymorphic variables (assignment polymorphism)polymorphic variables (assignment polymorphism)

overloading (ad hoc polymorphism)overloading (ad hoc polymorphism)

overriding (inclusion polymorphism)overriding (inclusion polymorphism)

deferred (abstract) methods deferred (abstract) methods

pure polymorphism (functions with polymorphic pure polymorphism (functions with polymorphic parameters) parameters)

generics or templates generics or templates

Page 7: Polymorphism  (Budd's UOOPJ, Ch. 12)

Polymorphic Variables Polymorphic Variables

Variable declared as one class can hold Variable declared as one class can hold valuevalues s from subclass from subclass

Dynamic (run-time) type must be subclass of Dynamic (run-time) type must be subclass of static (declared) type static (declared) type

In C++, only works with pointers and references In C++, only works with pointers and references

Polymorphic variables (or values) basis for power Polymorphic variables (or values) basis for power of OOP of OOP

Page 8: Polymorphism  (Budd's UOOPJ, Ch. 12)

OverloadingOverloading

A single function A single function namename denoting two or more function denoting two or more function bodiesbodies is is overloadedoverloaded

Common example: + means both integer and floating addition Common example: + means both integer and floating addition In Java, + also used for string concatenation In Java, + also used for string concatenation

Determination of which function to execute made by examining Determination of which function to execute made by examining argument/return types argument/return types

Bound either at compile-time or at run-time depending on languageBound either at compile-time or at run-time depending on language

Should not be confused with overriding or refinement – functions Should not be confused with overriding or refinement – functions need not be related by classes need not be related by classes

Should not be confused with Should not be confused with coercioncoercion (casting) – one type is (casting) – one type is converted into another for operation converted into another for operation

Page 9: Polymorphism  (Budd's UOOPJ, Ch. 12)

Overloading Example: FloristOverloading Example: Florist

class Spouse class Spouse { { public void sendFlowersTo(Address inAddress) public void sendFlowersTo(Address inAddress) { { go to florist; go to florist; give florist message give florist message sendFlowersTo(anAddress); sendFlowersTo(anAddress); } } }}

Page 10: Polymorphism  (Budd's UOOPJ, Ch. 12)

Overloading Example: FloristOverloading Example: Floristclass Florist class Florist { { public void sendFlowersTo(Address anAddress)public void sendFlowersTo(Address anAddress) { { if (address is nearby) if (address is nearby) { { make up flower arrangement; make up flower arrangement; tell delivery person sendFlowersTo(anAddress); tell delivery person sendFlowersTo(anAddress); } else { } else { look up florist near anAddress; look up florist near anAddress; contact other florist; contact other florist; give other florist message sendFlowersTo(anAddress); give other florist message sendFlowersTo(anAddress); } } } } } }

Above the Above the sendFlowersTosendFlowersTo methods are semantically related but not methods are semantically related but not related via inheritance related via inheritance Methods with same name not necessarily related semantically Methods with same name not necessarily related semantically

Page 11: Polymorphism  (Budd's UOOPJ, Ch. 12)

Overloading and Overloading and Type SignaturesType Signatures

Selection of which procedure to execute based on Selection of which procedure to execute based on type type signaturesignature – the number, types, and order of parametersthe number, types, and order of parameters– parametric overloadingparametric overloading

Often used in constructors Often used in constructors

C++ and Java allow functions in same scope to have C++ and Java allow functions in same scope to have same name if signatures differ same name if signatures differ

C++ also allows extensive overloading of operator C++ also allows extensive overloading of operator symbols symbols

Page 12: Polymorphism  (Budd's UOOPJ, Ch. 12)

Overloading and Overloading and Type Signatures (continued)Type Signatures (continued)

Polymorphic symbol Polymorphic symbol <<<< used for both used for both left shiftleft shift and and stream stream outputoutput – latter also overloaded by type of value – latter also overloaded by type of value

stream << integer; stream << integer; stream << char; stream << char; stream << char *; stream << char *; stream << double; stream << double; stream << complex; stream << complex;

Page 13: Polymorphism  (Budd's UOOPJ, Ch. 12)

Overriding Overriding

Overriding occurs when child class changes meaning of Overriding occurs when child class changes meaning of function from parent function from parent

Different child classes can override in different waysDifferent child classes can override in different ways– replacement or refinement replacement or refinement

Parent class can have default behavior; child classes Parent class can have default behavior; child classes alternatives alternatives

Contributes to code sharing Contributes to code sharing

Ensures common interfaces Ensures common interfaces

Page 14: Polymorphism  (Budd's UOOPJ, Ch. 12)

Example: Comparisons Example: Comparisons

abstract class Magnitude { abstract class Magnitude { public boolean lessOrEqual(Magnitude arg) public boolean lessOrEqual(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return (this.lessThan(arg) || this.equals(arg)); return (this.lessThan(arg) || this.equals(arg)); } } public boolean greaterOrEqual(Magnitude arg) public boolean greaterOrEqual(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return arg.lessOrEqual(this); return arg.lessOrEqual(this); } } public boolean lessThan(Magnitude arg) public boolean lessThan(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return this.lessOrEqual(arg) && ! this.equals(arg); return this.lessOrEqual(arg) && ! this.equals(arg); } } public boolean greaterThan(Magnitude arg) public boolean greaterThan(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return arg.lessThan(this); return arg.lessThan(this); } } }}

Page 15: Polymorphism  (Budd's UOOPJ, Ch. 12)

Example: Comparisons Example: Comparisons (continued)(continued)

class IncomparableMagnitudeException extends Exception class IncomparableMagnitudeException extends Exception { { public IncomparableMagnitudeException() { } public IncomparableMagnitudeException() { } public IncomparableMagnitudeException(String msg) public IncomparableMagnitudeException(String msg) { super(msg); } { super(msg); } } }

To define all six comparisons in a noncircular manner, To define all six comparisons in a noncircular manner, subclasses must: subclasses must:

Override class Override class ObjectObject method method equals()equals() if default not appropriate if default not appropriate

Override class Override class MagnitudeMagnitude method method lessThan()lessThan() or or lessOrEqual()lessOrEqual()

Page 16: Polymorphism  (Budd's UOOPJ, Ch. 12)

Example: Comparisons Example: Comparisons (continued)(continued)

class Point extends Magnitude class Point extends Magnitude { { public Point(int x0, int y0) public Point(int x0, int y0) { x = x0; y = y0; }{ x = x0; y = y0; }

public boolean lessThan(Magnitude arg) public boolean lessThan(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { if (arg instanceof Point) { if (arg instanceof Point) { Point p = (Point) arg; // less if lower left quadrant Point p = (Point) arg; // less if lower left quadrant return x < p.x && y < p.y; // of this point return x < p.x && y < p.y; // of this point } else throw new IncomparableMagnitudeException(); } else throw new IncomparableMagnitudeException(); } } private int x; private int y; private int x; private int y; } }

Note: The above method uses inheritance by limitation because of the Note: The above method uses inheritance by limitation because of the check for the Point type and throwing the exception check for the Point type and throwing the exception

Page 17: Polymorphism  (Budd's UOOPJ, Ch. 12)

Deferred (Abstract) MethodsDeferred (Abstract) Methods

Deferred method is special case of overridingDeferred method is special case of overriding

Parent class gives type signature, but provides no implementation Parent class gives type signature, but provides no implementation

Child class Child class mustmust provide an implementation provide an implementation

Usually combined with other techniques Usually combined with other techniques

Method included in parent class because it fits in abstraction, although no Method included in parent class because it fits in abstraction, although no concrete definition may be possible at that level concrete definition may be possible at that level semantics of abstract methods should be specified carefully – e.g., using pre- semantics of abstract methods should be specified carefully – e.g., using pre-

and postconditions. and postconditions. subclasses should adhere to specification subclasses should adhere to specification

Allows the deferred method to be applied to polymorphic variables of the Allows the deferred method to be applied to polymorphic variables of the parent typeparent type

In Java, use In Java, use abstractabstract modifier for method modifier for method

Page 18: Polymorphism  (Budd's UOOPJ, Ch. 12)

Pure Polymorphism Pure Polymorphism

Pure polymorphism usually means functions with polymorphic parameters Pure polymorphism usually means functions with polymorphic parameters (including receiver) (including receiver)

Method Method betweenbetween (like the other methods of Magnitude) exhibits pure (like the other methods of Magnitude) exhibits pure polymorphism polymorphism

class Magnitude class Magnitude { ... { ... public boolean between(Magnitude low, Magnitude high) public boolean between(Magnitude low, Magnitude high) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return low.lessOrEqual(this) && return low.lessOrEqual(this) &&

this.lessOrEqual(high); this.lessOrEqual(high); } } } }

Works for any receiver or arguments of parent type Works for any receiver or arguments of parent type MagnitudeMagnitude (generates (generates exception if of incomparable types) exception if of incomparable types)

Page 19: Polymorphism  (Budd's UOOPJ, Ch. 12)

Pure Polymorphism (continued)Pure Polymorphism (continued)

Code below would print "Is Between" Code below would print "Is Between"

Point p = new Point(0,0); Point p = new Point(0,0); Point q = new Point(10,10); Point q = new Point(10,10); Magnitude r = new Point(0,0); Magnitude r = new Point(0,0); if (r.between(p,q)) if (r.between(p,q)) System.println("Is Between"); System.println("Is Between"); else else System.printlnSystem.println ("Is Not Between"); ("Is Not Between");

Page 20: Polymorphism  (Budd's UOOPJ, Ch. 12)

Pure Polymorphism (continued)Pure Polymorphism (continued)

Message Message r.between(p,q)r.between(p,q) has the following trace of dynamic binding: has the following trace of dynamic binding: In code above, checks for In code above, checks for between()between() in Pointin Point, not found , not found In code above, checks for In code above, checks for between()between() in in MagnitudeMagnitude, found, binds call , found, binds call In In Magnitude.between,Magnitude.between, checks for checks for lessOrEqual()lessOrEqual() in in PointPoint, not found , not found In In Magnitude.between,Magnitude.between, checks for checks for lessOrEqual()lessOrEqual() in in MagnitudeMagnitude, found, binds , found, binds

call call In In Magnitude.lessOrEqualMagnitude.lessOrEqual, checks for , checks for lessThan()lessThan() in in PointPoint, found, binds call , found, binds call In In Point.lessThanPoint.lessThan, returns , returns falsefalse since (0,0) is not less than (0,0) since (0,0) is not less than (0,0) In In Magnitude.lessOrEqualMagnitude.lessOrEqual, checks for , checks for equals()equals() in in PointPoint, not found , not found In In Magnitude.lessOrEqualMagnitude.lessOrEqual, checks for , checks for equals()equals() in in MagnitudeMagnitude, not found , not found In In Magnitude.lessOrEqualMagnitude.lessOrEqual, checks for , checks for equals()equals() in in ObjectObject, found, binds call , found, binds call In In Object.equalsObject.equals, returns , returns truetrue In In Magnitude.lessOrEquaMagnitude.lessOrEqual, returns l, returns truetrue since (0,0) <= (0,0) since (0,0) <= (0,0) Similar for comparison of (0,0) and (10,10) ... Similar for comparison of (0,0) and (10,10) ... In In Magnitude.betweenMagnitude.between, returns , returns truetrue since (0,0) <= (0,0) and (0,0) <= (10,10), l since (0,0) <= (0,0) and (0,0) <= (10,10), l

Note that polymorphism (dynamic binding) takes more execution time than a Note that polymorphism (dynamic binding) takes more execution time than a static bindingstatic binding

Page 21: Polymorphism  (Budd's UOOPJ, Ch. 12)

Generics and Templates Generics and Templates

A A typetype can be used as a can be used as a parameterparameter in class description in class description

C++ example: C++ example:

template <class T> class Link template <class T> class Link { {

public: public: ... ... private: private:

T value; T value; Link * nextLink; Link * nextLink;

} }

Page 22: Polymorphism  (Budd's UOOPJ, Ch. 12)

Generics and Templates Generics and Templates (continued)(continued)

Declaration of variable provides the actual type Declaration of variable provides the actual type

Link<Shape> sl;Link<Shape> sl; Declaration above makes Declaration above makes s1s1 a a LinkLink variable that has variable that has

a value of type a value of type ShapeShape

Generics not supported in Java currently, but Generics not supported in Java currently, but may be in the future may be in the future

Keyword Keyword genericgeneric reserved reserved

Experimental versions of Java do support generics Experimental versions of Java do support generics

Page 23: Polymorphism  (Budd's UOOPJ, Ch. 12)

Review of Polymorphism in JavaReview of Polymorphism in Java

Polymorphic variables? Polymorphic variables? YesYes Tree-structured subclass hierarchy using inheritance Tree-structured subclass hierarchy using inheritance

(extends) (extends) Subtype hierarchies using interfaces (implements) Subtype hierarchies using interfaces (implements) Variables declared with either class or interface as Variables declared with either class or interface as

type type Variables can hold value from subclass or interface Variables can hold value from subclass or interface

subtype subtype

Overloading? Overloading? YesYes Overloading of method names (including in same Overloading of method names (including in same

class with parametric overloading) class with parametric overloading) No user-defined overloading of operator symbols No user-defined overloading of operator symbols

Page 24: Polymorphism  (Budd's UOOPJ, Ch. 12)

Review of Polymorphism in JavaReview of Polymorphism in Java

Overriding? Overriding? YesYes By default, all methods can be overridden By default, all methods can be overridden Keyword Keyword finalfinal prevents overriding prevents overriding

Deferred methods? Deferred methods? YesYes Keyword Keyword abstractabstract for deferred methods, signature but no for deferred methods, signature but no

body body

Pure polymorphism? Pure polymorphism? YesYes Dynamic binding of call to method, searching up subclass Dynamic binding of call to method, searching up subclass

hierarchy hierarchy

Generics? Generics? NoNo Perhaps in future Perhaps in future Experimental versions such as GJ (Generic Java) Experimental versions such as GJ (Generic Java)

Page 25: Polymorphism  (Budd's UOOPJ, Ch. 12)

Efficiency and Polymorphism Efficiency and Polymorphism

Programming always involves compromises Programming always involves compromises

Polymorphism is a compromise between Polymorphism is a compromise between efficiency and ease of development, use and efficiency and ease of development, use and maintenance maintenance

Ask yourself: whose time is more importantAsk yourself: whose time is more important– yours or the computer's? yours or the computer's?