Polymorphism means different forms or the ability to take on different forms. It is the ability of an entity to become attached to objects of various types. In order for a programming language to have true polymorphism it must have dynamic binding. Table 1 shows some common object-oriented programming languages which support polymorphism.
Operations that have multiple meanings,
depending on the type of object they are attached to at run time, are known
as polymorphic operations. An example of a polymorphic operator is
the C++ keyword write. Figure 1 shows an example of how objects
could be assigned using polymorphism.
|
|
|
|
|
|
|
|
|
|
|
P : Polygon;
-- valid assignments P := R;
|
Do not confuse polymorphism with overloading. Overloading assigns a type to a distinct operation. Polymorphism is determined at run time while overloading can be determined at compile time.
When polymorphism is associated with static binding it is normally called ad hoc polymorphism.
Figure 2 shows and example of polymorphism
using C++.
| #include <iostream.h>
void function (int x); class shape { public: int pubint; shape(): pubint (88) { cout << "\nin shape default constructor";}; shape (int i): pubint (i) { cout << "\nin shape int constructor";}; virtual void draw (){ cout << "\nIN CLASS SHAPE\n"; cout << "\n sh.pubint is: " << pubint; return; }; }; // end of shape class class rectangle: public shape
class square : public rectangle
int main()
___________________________________________________________ When you run this program you will get the following output
You are now in main in shape default constructor
IN CLASS RECTANGLE rt.pubint is: 77
sh.pubint is: 88 variable is: 9644
|
Figure 3 is a program example taken
from the book Ada 95 From the Beginning showing an example of dynamic
binding and polymorphism.
| package Vehicle_Package is
type Vehicle is tagged private; procedure Give_Info(V: Vehicle); type Motor_Vehicle is
new Vehicle with private;
type Private_Car is
new Motor_Vehicle with private;
type Van is
new Motor_Vehicle with private;
type Bus is
new Motor_Vehicle with private;
type Minibus is new Bus with private; private
type Motor_Vehicle isnew
Vehicle with
type Private_Car isnew
Motor_Vehicle with
type Van is new
Motor_Vehicle with
type Bus is new
Motor_Vehicle with
type Minibus isnew
Bus with
package body Vehicle_Package is
procedure Give_Info (M
: Motor_Vehicle) is
procedure Give_Info (P
: Private_Car) is
procedure Give_Info (Motor_Vehicle(VN:
Van)) is
procedure Give_Info (B:
Bus) is
|
According to the Ada 95 Reference Manual, run-time polymorphism is achieved when a dispatching operation is called by a dispatching call.
The primitive subprograms of a tagged
type are called dispatching operations. A call is termed a dispatching
call when the controlling tag can be dynamically determined, in which case
the call dispatches to a body that is determined at run time.
Go to Dynamic binding or the Table of Contents