e Polymorphism

Polymorphism

The sender of a message does not need to know the receiver's class

In an earlier example there was a class Vehicle with several subclasses, such as Car, Plane and Bicycle.

All vehicles offered an operation stop, but let us assume that the different types of vehicles should behave slightly differently when requested to stop, so we let each subclass have its own stop method.

However, the part of the program which is responsible for stopping the vehicles, may simply send stop messages to vehicles and need not know that there are different subclasses of vehicles, and that instances of these classes will behave differently when asked to stop.

The effect is that upon receiving the message the object knows what class it belongs to, and thus executes the stop method for its own class.

This is an example of polymorphism. It serves the purpose of structuring systems around WHAT is to be done, and allows details about HOW classes and methods are implemented to be hidden.

The alternative solution in this case, would have been for the sender to ask every receiving Vehicle for its type, and thereafter execute a version of the stop function which corresponds to this type.


Here is Grady Booch's definition of the term polymorphism:

A concept in type theory, according to which a name (such as a variable declararation) may denote objects of many different classes that are related by some common superclass; thus, any object denoted by this name is able to respond to some common set of operations in different ways.


If you are interested in having another example on polymorphism; look at the exercise on inheritance, if you haven't done that already!

An example of how polymorphism may simplify an ordinary program.

How does this really work? Static vs. Dynamic binding of functions.


previous | next | start | contents | dictionary | help | evaluation

© Ericsson Telecom AB, 1995, Stockholm, Sweden