Saturday, May 7, 2011

POLYMORPHISM

The word polymorphism means “many forms.” When a subclass overrides a method of a superior class, the
behavior of the method will depend upon which type of object is being used in the program, an instance of the
superior class or an instance of the subclass. This characteristic of OO programming is called polymorphism,
and it is a powerful feature of the OO approach.
We will add some lines to our AutomobileFactory class to set the speed of a family car to 120 and
set the speed of a sports car to 120. Looking back at the accelerate() method for the class Automobile,
you will see that the maximum speed for an instance of the Automobile class is 70. Compare that with the
accelerate() method for the SportsCar class; the top speed for a SportsCar is 150.
When we call the same accelerate() method for an instance of Automobile and an instance of
SportsCar, the results are different. The Automobile speeds up to 70, and the SportsCar speeds up to
120. To show this, add code to the AutomobileFactory class:
/**
* Class AutomobileFactory
* @author Carl Reynolds
*/
class AutomobileFactory {
.
.
.
family = new Automobile(
"VW", "Passat", 2002, 170 );
sports = new SportsCar(
"Ford", "Mustang", 2005, 300 );
.
.
.
//same method call to instances of 2 different classes
family.accelerate(120. );
sports.accelerate(120. );
//polymorphism will cause the effects to be different
System.out.println( family + " " + family.getSpeed() );
System.out.println( sports + " " + sports.getSpeed() );
}
This will be the new output:
3 Automobiles
2006 Kia Rio
2002 VW Passat
2005 Ford Mustang
2002 VW Passat 70.0
2005 Ford Mustang 120.0
Polymorphism allows us to write programs in a more general way. We can reference the superior class as
we write programs, and if the object being used by the program happens to belong to a subclass of the superior
class, the methods in the subclass which override the corresponding methods in the superior class will insure that
methods appropriate to the particular instance will be called. This is another way in which OO programming
reduces the amount of code that must be written and tested, and also promotes reuse of existing code in new
applications.

No comments:

Post a Comment