interface to access a general class of actions. The specific action is determined by the
exact nature of the situation. A simple example of polymorphism is found in the
steering wheel of an automobile. The steering wheel (i.e., the interface) is the same no
matter what type of actual steering mechanism is used. That is, the steering wheel
works the same whether your car has manual steering, power steering, or rackand
pinion steering. Therefore, once you know how to operate the steering wheel, you can
drive any type of car.
The same principle can also apply to programming. For example, consider a stack
(which is a firstin, lastout list). You might have a program that requires three different
types of stacks. One stack is used for integer values, one for floatingpoint values, and
one for characters. In this case, the algorithm that implements each stack is the same,
even though the data being stored differs. In a nonobjectoriented language, you would
be required to create three different sets of stack routines, with each set using different
names. However, because of polymorphism, in Java you can create one general set of
stack routines that works for all three specific situations. This way, once you know how
to use one stack, you can use them all.
More generally, the concept of polymorphism is often expressed by the phrase “one
interface, multiple methods.” This means that it is possible to design a generic interface
to a group of related activities. Polymorphism helps reduce complexity by allowing the
same interface to be used to specify a
general class of action. It is the compiler’s job to
select the
specific action (i.e., method) as it applies to each situation. You, the
programmer, don’t need to do this selection manually. You need only remember and
utilize the general interface.
Inheritance
Dostları ilə paylaş: