The term polymorphism means “many forms” and,
in object-oriented programming, it refers to the ability to define
more than one class with the same interface. There are many
programming tasks that can benefit from the use of
polymorphism.
For instance, suppose you’re writing a program
to handle vehicles and you know that you’ll have a Car class and a
Truck class. Both of these classes will need a Drive() method and a
Turn() method, so this would be a good instance to use
polymorphism. To start, follow these three steps to define a more
general class called Vehicle:
- Add a new Class Module to your project.
- Change its name to Vehicle.
- Add the following code to the class
module:
Public Sub Drive(Speed As Integer)
End Sub
Public Sub Turn(Direction As Single)
End Sub
This defines the interface—two methods named
Drive and Turn with their specified arguments. The interface could
also include properties as well as methods. Note that the
methods—and properties, if there were any—are empty (you’ll see
why in a minute).
Now follow these three steps to create a class
that implements the Vehicle interface:
- Add a new
Class Module to your project. - Change its
name to Car. - Add the
following code to the class module:
Implements Vehicle
With the Car code window open, pull down the
Object list at the top left of the window. You’ll see that Vehicle
is listed there. When you select Vehicle, the members of its
interface—namely, the methods Drive and Turn—become available in
the Procedure list at the top right of the code window. Select one
of the methods to enter it in the Car class. The method is still
empty. Then, add the code to the method to implement it as needed
for this specific class. You would to do the same for the Truck
class and for any other classes that need the same interface, such
as Motorcycle and Bicycle.
Each of these classes is likely to implement
the methods differently. Car, for example, will have a higher top
speed than Bicycle, and Motorcycle will be able to turn more
quickly than Truck. But because all of these classes implement the
same interface, you know they’ll have Drive and Turn methods with
specified arguments. For example, you can call the method obj.Drive(25) on any object
regardless of whether it’s a Car, Truck, Motorcycle, or
Bicycle.
You can also add more members to an object’s
interface beyond the ones it implements from the base class. For
example, Car might have a MilesPerGallon property while Bicycle
would not. In any event, you should always implement the full
interface and not just part of it. After all, implementing an
interface is sort of a contract that the class will have with all
the members.
Advance your scripting skills to the next level with TechRepublic’s free Visual Basic newsletter, delivered each Friday. Automatically sign up today!