What Is Polymorphism?

Simply stated, polymorphism is the ability to have different classes implement a common interface in different ways. The interface of a class is defined by the properties and methods the class makes available. That is, the interface defines the way we programmers can access the properties and methods of a class (usually through the Public elements of the class).

Now that you know something about inheritance, let's add a little flesh to the example discussed in Chapter 2.

Chapter 2 discusses an example in which there is a Doctor object, a Nurse object, a Patient object, and a Visitor object ”all placed in a hospital setting. (Although Chapter 2 doesn't say so, perhaps each of these objects is derived from a base class object called HospitalPerson .)

In the example in Chapter 2, when you issue the message DoSomething() , each object reacts to the message in its own way: In response to the DoSomething() message, the Doctor object performs an operation, the Nurse object gives the Patient object an injection, the Patient object says "Ouch" and complains, and the Visitor object says, "I'll bet that hurt." Note that each object reacts differently to the same message. This is polymorphism in action ”different objects ( Doctor , Nurse , and so on) reacting differently (for example, an operation by the Doctor , an injection by Nurse ) to the same interface (that is, a DoSomething() message).

This is pretty heady stuff. Because a derived class object inherits the capabilities of the base class, any derived class object can be treated as if it were a base class object. This extensibility, however, is a one-way street. Drawing on the Building class example from Chapter 17, "Inheritance," you can say that Home "is a" Building because Home is a derived class of Building . However, you cannot say a Building always "is a" Home because a Building could also be an apartment or a commercial building (that is, an Apartment or a Commercial class). Still, inheritance coupled with polymorphism allows you to do some very useful things that would not be possible otherwise .

Visual Basic .NET. Primer Plus
Visual Basic .NET Primer Plus
ISBN: 0672324857
EAN: 2147483647
Year: 2003
Pages: 238
Authors: Jack Purdum

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net