Polymorphism:
- Ways the Language allows you to code routines with the
same
identifier but the actual parameters can be of different types.
- Polymorphism is a bad term to use.
- Helpful definitions:
- "A function or operator is polymorphic
is it has at least two possible types."1
"A function or operator exhibits ad
hoc polymorphism
if it
has at least two but only finitely
many
possible types."1
"A function or operator exhibits universal
polymorphism if it has infinitely many possible types"
Overloading
- When the same symbol translates to different code based on
the
(static) actual parameter types:
We say that the operator/function is overloaded.
- Which code is usually bound statically (before runtime)
- In most languages ‘+’ corresponds to
different code i.e.:
Vs
- Java adds another meaning to ‘+’
- Ada and C++ allow users to overload operators.
- The interaction between overloading and coercion can be
very
tricky.
- C has no USER overloading -- operators or functions
- Java does not allow users to overload operators.
- Overload
Example from Ada
Dangerous Overloading of Operators
- C
z = &y /* assign the address of y to x */
z = x & y /*assign the bit-wise AND of x and y */-
Fortran:
( If SUM=20 and COUNT=30 are integers and AVG is a real variable. Then
AVG will be 0.0) - Pascal uses a different symbols for
integer
division and real division. div vs ‘/’
- Ada makes the above statement illegal since the types do
not
match!
Inclusion Polymorphism Also called subtype
Polymorphism---
- A function or operator exhibits inclusion(subtype) polymorphism
if one or
more
of its parameter type have subtypes.
- Ada, Pascal, Haskell, small talk, C++ and Java allow
subtyping.
Object Oriented Programming Languages
are characterized by their support of 4 facilities
- Encapsulation
- Inheritance
- Inclusion polymorphism
- Dynamic binding of function calls to function bodies
(dynamic
dispatching)
Object Oriented languages without CLASSES
- Prototype-based languages
- Self, JavaScript
- No constructors -- new objects are created from scratch
by
listing all methods
- Usually dynamically typed.
- Usually very small amount of encapsulation
- No static inheritance -- uses a
dynamic mechanism
called delegation
- What is a Computer?
Class
Based - lists
|
Prototyped
Base |
|
|
Parametric Polymorphism
to be discussed later.