Term
used in several different ways in computer science
Polymorphism in Programming Languages
Polymorphism in Untyped Languages
Polymorphism is a trivial issue in untyped languages.
All variables are potentially polymorphic.
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
Forms of Polymorphism
Polymorphic Variables
Variable
declared as one class can hold (value)s from subclass
Overloading
A
single function name
denoting two or more function
bodies
is overloaded
Overloading Example: Florist
Procedure
Spouse.sendFlowersTo(anAddress : address);
begin
go to florist;
give florist message sendFlowersTo(anAddress);
end;
Procedure
Florist.sendFlowersTo(anAddress : address);
begin
if address is nearby then
make up flower arrangement
tell delivery person sendFlowersTo(anAddress);
else
look up florist near anAddress
phone florist
give florist message sendFlowersTo(anAddress)
end;
end;
Type Signatures
stream << integer;
stream << char;
stream << char *;
stream << double;
stream << complex;
Overriding
Overriding occurs when child class changes meaning of function from parent
Example -- from class Magnitude
smalltalk
{<=}
arg
^ self < arg or: [ self = arg ]
{>=}
arg
^ arg <= self
{<}
arg
^ self <= arg and: [ self ~= arg ]
{>}
arg
^ arg < self
Overridden Methods
Child
classes need only override one method (e.g., $<$) to get effect
of all relationals
Portable Algorithms
Deferred Methods
Deferred Method in C++
class
Shape {
public:
Point corner;
void virtual draw() = 0; // deferred member function
};
class
Circle : public Shape {
public:
int radius;
void draw() { drawCircle(corner + radius, radius); }
};
Pure Polymorphism
Smalltalk Example
The between:and: method occurs in class Magnitude
Recall earlier discussion of relationals to see variety of uses
{between:}
low {and:} high
" test to see if the receiver is between two endpoints "
^ (low <= self) and: [ self <= high ]
Generics and Templates
A
type can be used as a parameter in class description
template
<class T> class link {
public:
T value;
link<T> * nextLink;
};
The
declaration of variable provides the actual type
Polymorphism in Java
-- Subtype hierarchies using interfaces ( implements)
-- Variables declared with either class or interface as type
-- Variables can hold value from subclass or interface subtype
-- No user-defined overloading of operator symbols
Polymorphism in Java (continued)
-- Keyword {\sf final} prevents overriding
Efficiency and Polymorphism