Polymorphism refers to the ability of executing different operations
in response to the same message. Polymorphism can also be static or
dynamic. In dynamic polymorphism the response to the message is decided
on run-time while in static polymorphism it is decided out of run-time
(i.e. on compile-time). The mechanism used to link the message with
the method in dynamic polymorphism is known as late or dynamic binding
while if the linking is done on compile time it is known as early
or static binding.
Polymorphism is implemented using four different mechanisms:
- Overloading: an operation name refers to two different method
implementations that differs either in its scope or signature. It
uses early binding.
- Generics: also called templates, they define a way to
declare generic classes parameterizing some of its types. It uses
- Overriding: a derived class re-defines a method inherited from
the base class. It may use late binding.
- Polymorphic variable: also called assignment polymorphism,
it refers to a variable that can have different types during execution.
By performing an upcast we convert a variable referring to
an object of a derived class to one referring to its base class. It
is the most common situation for using a polymorphic variable as we
can ensure that a derived object can always be treated as one of its
base class. On the other hand if we convert an object of base class
to one of its derived class we are performing a downcast. In
this case we cannot ensure the correctness of the operation unless
the variable had been previously upcasted. Assignment polymorphism
is known as pure polymorphism if the variable is used as a
parameter of an operation. It uses late binding.