Presentation is loading. Please wait.

Presentation is loading. Please wait.

Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.

Similar presentations


Presentation on theme: "Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes."— Presentation transcript:

1 Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes

2 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 (Addison-Wesley, 2000) Created: 14 August 2004 Revised: 1 April 2010

3 Definition Polymorphous  Having, or assuming, various forms, characters, or styles (Webster's Collegiate Dictionary, Fifth Edition). Term used in several different ways in computer science 1

4 Polymorphism in Programming Languages A variable holding a value drawn from a group of types A name associated with several different function bodies A single function with polymorphic variables as parameters 2

5 Polymorphism in Untyped Languages Polymorphism is trivial issue in untyped languages All variables are potentially polymorphic Variables take on type of their values dynamically silly: x " a silly Smalltalk polymorphic method " (x isKindOf: Integer) ifTrue: [ ^ x + 1 ]. (x isKindOf: Fraction) ifTrue: [ ^ x reciprocal ]. (x isKindOf: String) ifTrue: [ ^ x reversed ]. ^ nil 3

6 Forms of Polymorphism Polymorphic variables (assignment polymorphism) Overloading (ad hoc polymorphism) Overriding (inclusion polymorphism) Deferred (abstract) methods Pure polymorphism (functions with polymorphic parameters) Generics or templates 4

7 Forms of Polymorphism Polymorphic Variables Variable declared as one class can hold values from subclass Dynamic (run-time) type must be subclass of static (declared) type In C++, only works with pointers and references Polymorphic variables (or values) basis for power of OOP 5

8 Forms of Polymorphism Overloading Overload  A single function name denoting two or more function bodies Common example  + means both integer and floating addition  In Java, + also used for string concatenation Determination of which function to execute made by examining argument/return types Bound either at compile-time or at run-time depending on language Should not  be confused with overriding or refinement – functions need not be related by classes  be confused with coercion (casting) – one type is converted into another for operation 6

9 Forms of Polymorphism Overloading Example: Florist class Spouse { public void sendFlowersTo(Address anAddress) { go to florist; give florist message sendFlowersTo(anAddress); } 7

10 Forms of Polymorphism Overloading Example: Florist (cont.) class Florist { public void sendFlowersTo(Address anAddress) { if (address is nearby) { make up flower arrangement; tell delivery person sendFlowersTo(anAddress); } else { look up florist near anAddress; contact other florist; give other florist message sendFlowersTo(anAddress); } Above the sendFlowersTo methods are semantically related but not related via inheritance Methods with same name not necessarily related semantically 8

11 Forms of Polymorphism Overloading and Type Signatures Selection of which procedure to execute based on type signature  The number, types, and order of parameters  Parametric overloading Often used in constructors C++ and Java allow functions in same scope to have same name if signatures differ C++ also allows extensive overloading of operator symbols 9

12 Forms of Polymorphism Overloading and Type Signatures (cont.) << Polymorphic symbol <<  Used for both left shift and stream output  Stream output also overloaded by type of value stream << integer; stream << char; stream << char *; stream << double; stream << complex; 10

13 Forms of Polymorphism Overriding Overriding occurs when child class changes meaning of function from parent Different child classes can override in different ways  Replacement or refinement Parent class can have default behavior; child classes alternatives Contributes to code sharing Ensures common interfaces 11

14 Forms of Polymorphism Overriding Example: Comparisons abstract class Magnitude { public boolean lessOrEqual(Magnitude arg) throws IncomparableMagnitudeException { return (this.lessThan(arg) || this.equals(arg)); } public boolean greaterOrEqual(Magnitude arg) throws IncomparableMagnitudeException { return arg.lessOrEqual(this); } public boolean lessThan(Magnitude arg) throws IncomparableMagnitudeException { return this.lessOrEqual(arg) && ! this.equals(arg); } public boolean greaterThan(Magnitude arg) throws IncomparableMagnitudeException { return arg.lessThan(this); } } 12

15 Forms of Polymorphism Overriding Example: Comparisons (cont.) class IncomparableMagnitudeException extends Exception { public IncomparableMagnitudeException() { } public IncomparableMagnitudeException(String msg) { super(msg); } } To define all six comparisons in a noncircular manner, subclasses must: Override class Object method equals() if default not appropriate Override class Magnitude method lessThan() or lessOrEqual() 13

16 Forms of Polymorphism Overriding Example: Comparisons (cont.) class Point extends Magnitude { public Point(int x0, int y0) { x = x0; y = y0; } public boolean lessThan(Magnitude arg) throws IncomparableMagnitudeException { if (arg instanceof Point) { Point p = (Point) arg; // less if lower left quadrant return x < p.x && y < p.y; // of this point } else throw new IncomparableMagnitudeException(); } private int x; private int y; } Note: The above method uses inheritance by limitation because of the check for the Point type and throwing the exception 14

17 Forms of Polymorphism Deferred (Abstract) Methods Deferred method is special case of overriding Parent class gives type signature, but provides no implementation Child class must provide an implementation Usually combined with other techniques Method included in parent class because it fits in abstraction, although no concrete definition may be possible at that level  Semantics of abstract methods should be specified carefully – e.g., using pre- and postconditions.  Subclasses should adhere to specification Allows the deferred method to be applied to polymorphic variables of the parent type In Java, use abstract modifier for method 15

18 Forms of Polymorphism Pure Polymorphism Pure polymorphism usually means functions with polymorphic parameters (including receiver) Method between (like the other methods of Magnitude) exhibits pure polymorphism class Magnitude {... public boolean between(Magnitude low, Magnitude high) throws IncomparableMagnitudeException { return low.lessOrEqual(this) && this.lessOrEqual(high); } Works for any receiver or arguments of parent type Magnitude (generates exception if of incomparable types) 16

19 Forms of Polymorphism Pure Polymorphism (cont.) Point p = new Point(0,0); Point q = new Point(10,10); Magnitude r = new Point(0,0); if (r.between(p,q)) System.println("Is Between"); else System.println("Is Not Between"); Print "Is Between" 17

20 Forms of Polymorphism Pure Polymorphism (cont.) Message r.between(p,q) has the following trace of dynamic binding:  In code above, checks for between() in Point, not found  In code above, checks for between() in Magnitude, found, binds call  In Magnitude.between, checks for lessOrEqual() in Point, not found  In Magnitude.between, checks for lessOrEqual() in Magnitude, found, binds call  In Magnitude.lessOrEqual, checks for lessThan() in Point, found, binds call  In Point.lessThan, returns false since (0,0) is not less than (0,0)  In Magnitude.lessOrEqual, checks for equals() in Point, not found  In Magnitude.lessOrEqual, checks for equals() in Magnitude, not found  In Magnitude.lessOrEqual, checks for equals() in Object, found, binds call  In Object.equals, returns true  In Magnitude.lessOrEqual, returns true since (0,0) <= (0,0)  Similar for comparison of (0,0) and (10,10)...  In Magnitude.between, returns true since (0,0) <= (0,0) and (0,0) <= (10,10), l Note that polymorphism (dynamic binding) takes more execution time than a static binding 18

21 Forms of Polymorphism Generics and Templates A type can be used as a parameter in class description C++ example: template class Link { public:... private: T value; Link * nextLink; } 19

22 Forms of Polymorphism Generics and Templates (cont.) Declaration of variable provides the actual type  Link sl;  Declaration above makes s1 a Link variable that has a value of type Shape Generics not supported in Java originally, but suppor was added later Scala supports generics 20

23 Review of Polymorphism in Java Polymorphic variables? Yes  Tree-structured subclass hierarchy using inheritance (extends)  Subtype hierarchies using interfaces (implements)  Variables declared with either class or interface as type  Variables can hold value from subclass or interface subtype Overloading? Yes  Overloading of method names (including in same class with parametric overloading)  No user-defined overloading of operator symbols 21

24 Review of Polymorphism in Java (cont.) Overriding? Yes  By default, all methods can be overridden  Keyword final prevents overriding Deferred methods? Yes  Keyword abstract for deferred methods, signature but no body Pure polymorphism? Yes  Dynamic binding of call to method, searching up subclass hierarchy Generics? Not originally, but added later  Implemented with type erasure on JVM, so generic type information is lost at runtime 22

25 Efficiency and Polymorphism Programming always involves compromises Polymorphism is a compromise between efficiency and ease of development, use and maintenance Ask yourself: whose time is more important  yours or the computer's? 23

26 Acknowledgement 24 This work was supported by a grant from Acxiom Corporation titled “The Acxiom Laboratory for Software Architecture and Component Engineering (ALSACE).”


Download ppt "Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes."

Similar presentations


Ads by Google