18.16. Polymorphism


There are two powerful aspects to inheritance. One is code reuse. When you create a ListBox class, you're able to reuse some of the logic in the base (Window) class.

What is arguably more powerful, however, is the second aspect of inheritance: polymorphism .

When the phone company sends your phone a ring signal, it does not know what type of phone is on the other end of the line. You might have an old-fashioned Western Electric phone which energizes a motor to ring a bell, or you might have an electronic phone which plays digital music.

As far as the phone company is concerned, it knows only about the "base type" phone and expects that any "instance" of this type knows how to ring. When the phone company tells your phone to ring, it simply expects the phone to "do the right thing." Thus, the phone company treats all the phones it connects to polymorphically.

18.16.1. Creating Polymorphic Types

Because a ListBox is-a Window and a Button is-a Window, we expect to be able to use either of these types in situations that call for a Window. For example, a form might want to keep a collection of all the instances of Window it manages so that when the form is opened, it can tell each Window to draw itself. For this operation, the form does not want to know which windows are actually ListBoxes and which are Buttons; it just wants to tick through its collection and tell each to "Draw." In short, the form wants to treat all its Window objects polymorphically.

18.16.2. Creating Polymorphic Methods

To create a method that supports polymorphism, you need only mark it as Overridable in its base class. For example, to indicate that the method DrawWindow of the window class is polymorphic, simply add the keyword Overridable to its declaration, as follows:

 Public Overridable Sub DrawWindow(  ) 

Now, each derived class is free to implement its own version of DrawWindow and the method will be invoked polymorphically. To do so, you simply override the base class overridable method by using the keyword Overrides in the derived class method definition, and then add the new code for that overridden method:

 Public Overrides Sub DrawWindow(  )     MyBase.DrawWindow(  ) ' invoke the base method     Console.WriteLine( _       "Writing string to the listbox: {0}", listBoxContents) End Sub 'DrawWindow 

The keyword Overrides tells the compiler that this class has intentionally overridden how DrawWindow works. Similarly, you'll override this method in another class, Button, also derived from Window.

See the sidebar "Versioning with New and Override" for more information on the Overrides keyword.




Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

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