Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 10.  Inheritance and Polymorphism


Polymorphism is a facility supported by Visual Basic .NET. Polymorphic behavior occurs when you declare a parent type and instantiate a child type. The compiler adds code to resolve the actual method that needs to be called by the instance of the object.

Continuing the plane example, we could add a MultiEngineLand plane to our plane class. Operations that use the same code to work with both kinds of plane could be written in one procedure. If we defined the parameters to the procedure to take a Plane, we could pass any subclass of plane to the procedure.

Polymorphic behavior is generally needed when you see code that takes an action based on a case statement evaluating a type code. Let's step back and look at polymorphism relative to our Plane class.

Suppose we only had one Plane class and a type code indicating two kinds of planes: single-engine and multi-engine planes. If we had a method Start() and used a type code to determine plane type, single-or multi-engine, we would implement Start() using a Select Case statement, as demonstrated in Listing 10.6.

Listing 10.6 Case statements are often indicative of a flat class that needs subclasses with polymorphic methods .
  1:  Namespace NeedsPolymorphism  2:  Public Enum PlaneType  3:  SingleEngineLand  4:  MultiEngineLand  5:  End Enum  6:   7:  Public Class Plane  8:  Private FType As PlaneType  9:   10:  Public Sub New(ByVal Type As PlaneType)  11:  MyBase.New()  12:  FType = Type  13:  End Sub  14:   15:  Public Sub Start()  16:  Select Case FType  17:  Case PlaneType.SingleEngineLand  18:  ' start engine 1  19:  Case PlaneType.MultiEngineLand  20:  ' start engines 1 and 2  21:  End Select  22:  End Sub  23:   24:  End Class  25:  End Namespace 

Plane contains an enumeration PlaneType that is used to decide how many engines to start, lines 15 to 22. However, this is a bad implementation. Single-engine planes do not actually have two engines, one of which we choose not to start. A single-engine plane has one engine that we start, and a multi-engine plane has more than one engine that we start. Clearly, there are two classes here. This is the exact kind of scenario that inheritance and polymorphism were designed to solve. By defining two subclasses of the abstract class Plane, we offload the case statement to the compiler (see Listing 10.7).


Generally, polymorphism is implemented using a virtual methods table an array of method pointersand a case statement based on type is replaced with an index into the method table.

The benefit to you is that you do not have to write and maintain if conditional or case statements every time you add a new type. In effect, the compiler manages the virtual methods table and resolves the call to the method based on type automatically.

Listing 10.7 By subclassing Plane, we can offload the case statement to the compiler.
  1:  Namespace ClassPlane  2:   3:  Public MustInherit Class Plane  4:  [...]  5:  Public MustOverride Sub Start()  6:  End Class  7:   8:  Public NotInheritable Class SingleEngineLand  9:  Inherits Plane  10:  [...]  11:  Public Overrides Sub Start()  12:  ' start 1  13:  End Sub  14:  End Class  15:   16:  Public NotInheritable Class MultiEngineLand  17:  Inherits Plane  18:  [...]  19:  Public Overrides Sub Start()  20:  ' start 1 and 2  21:  End Sub  22:   23:  End Class  24:   25:  End Namespace 

Notice that Listing 10.7 requires no case statement. You will not require a case statement anywhere else in your code either. The correct Start method will be called based on the type of plane you create, SingleEngineLand or MultiEngineLand. Further, if you add additional kinds of planes, you will not need to create or extend a case statement either. Simply implement the Start method for each kind of plane, and the compiler will resolve the method call via a virtual methods table.

Understanding the Three Kinds of Polymorphism

Polymorphic behavior can be implemented for properties and methods. (Keep in mind that property statements are really methods, as demonstrated by the callnot shownand the stack frame management and ret statement in the disassembly shown in Figure 10.5.) Polymorphic behavior can also be contrived relative to events by raising the event in an overridable procedure.

Figure 10.5. Property methods have all of the aspects of a method as shown in the disassembly.


Visual Basic .NET supports three kinds of polymorphism in comparison to VB6's one kind of polymorphism. Visual Basic .NET supports interface, inheritance, and abstract polymorphism. Each kind of polymorphism is described in the following subsections.

Interface Polymorphism

Interface polymorphism is the kind of polymorphic behavior carried over from VB6. Interface polymorphism means that multiple classes can implement an interface, or a single class can implement many interfaces.

The interface itself provides no implementation. The implementation is up to the user implementing that interface.

Define parameters as interface types and any object of any type that implements that interface can be passed as the argument for the parameter. The code behaves polymorphically based on the actual object passed and the way that object implements the interface.

Inheritance Polymorphism

Inheritance polymorphism supports multiple child classes inheriting from a single parent class. All child classes get a copy of everything in the parent class and can extend the parent by implementing additional members in the child class or overriding members in the base class.


You can invoke parent behavior from a child using the MyBase reference from the child method.

If you want to layer behavior on a member in a parent class, override the member and call MyBase. member in the child class and add the new behavior after the call to the parent behavior.

Child methods that override a parent method generally call the parent method first, followed by new behavior, but you are not obligated to do so.

Abstract Polymorphism

Abstract virtual methods must be implemented by a child class or the child class itself will be abstract. Abstract classes cannot be instantiated .


Some languages allow you to instantiate classes containing abstract methods, but calling the abstract method results in an exception.

Delphi's Object Pascal is an example of a language that supports creating instances of abstract classes; Visual Basic .NET does not support creating instances of abstract classes (that is, classes with the MustInherit modifier).

If you attempt to call an abstract method in a base class using MyBase, you will get an error similar to "The method 'Public MustOverride Property PropertyName() As String' is declared with 'MustOverride' and so cannot be called with 'MyBase'."

Implemented virtual methods are inherited from abstract base classes, and you must provide an implementation of abstract methods if you want to create instances of your child class.

Calling Inherited Methods

Methods inherited from a parent class are invoked using the MyBase reference. When you encounter MyBase. name , the code is invoking a method or property of the immediate ancestor of the class containing the call.

If you want to find out type information about the immediate ancestor, call MyBase. GetType. Debug.WriteLine(MyBase.GetType.Name) will write the name of the immediate ancestor to the Output Window.

Another internal reference is MyClass. MyClass is similar to Me but disregards the runtime type of the object. If you invoke a method using Me, the method invocation will behave polymorphically. MyClass does not behave polymorphically; MyClass calls the method defined in the actual class of the object when it was declared, not when it was instantiated.

Assume for debugging purposes that every type of plane needs the ability to write its tail number to the Output window. Because the behavior is the same and only the tail number query is polymorphic, we only need one implementation of WriteTailNumber in the base class Plane.

 Public MustInherit Class Plane   Public MustOverride Property TailNumber() As String   Public MustOverride Sub Start()   Public Sub WriteTailNumber()    Debug.WriteLine(Me.TailNumber)   End Sub End Class 

Me.TailNumber gets the correct tail number based on the runtime type of Me. If we changed the invocation to MyClass.TailNumber, Visual Basic .NET would attempt to read Plane.TailNumber, which is an abstract method and would result in a compiler error.

Use MyBase when you want to refer to the parent. Refer to MyClass when you want to refer to the containing class's reference to self, and Me when you need to refer to the actual instance, rather than the containing class.

Overriding a Parent Class Method

To designate a method as a virtual method, add the Overridable keyword to the procedure in the parent class. To override an overridable method defined in a parent class, define the method with an identical signature in the child class and add the Overrides modifier to the child class method.

Virtual Methods

For example, if we want to make WriteTailNumber virtual, we can revise the implementation in the Plane class, adding the Overridable modifier to the implementation.

 Public Overridable Sub WriteTailNumber()   Debug.WriteLine(TailNumber) End Class 

To override the method in a child class, reimplement the method, changing the modifier to Overrides:

 Public Overrides Sub WriteTailNumber()   ' New Code! End Sub 


You are not obligated to override virtual Overridable methods.

If you are satisfied with the implementation of a virtual method in a parent class, do not override the method in a child class.

Shadow Methods

As an alternative, suppose you have a method in a parent class and you want to reintroduce new behavior in a child class. Instead of making the consumer remember a new name for the same semantic operation, shadow the method.

You can use the Shadows modifierplaced in the same location as the Overrides or Overridable modifiersto conceal a method with the same signature in an ancestor. To completely replace the WriteTailNumber method in a child class, reimplement the method as follows :

 Public Shadows Sub WriteTailNumber()   ' New Implementation! End Sub 

There are several facts you need to know in addition to the grammar:

  • Shadows is required if you introduce a method in a child class with the same signature as a nonvirtual method in a parent.

  • Shadowed methods do not behave polymorphically. If you declare a reference as type parent and instantiate a child type, when you call the nonvirtual method you will not get the new method. The parent class method will be called. To call the shadowed method, the reference must be declared as a child class type.

  • Shadowed methods are not removed. You can invoke shadowed behavior using the MyBase reference.

Shadowed methods are not polymorphic. The Shadows modifier allows you to reintroduce behavior for nonvirtual methods and will avoid a compiler error, but shadowed method calls are not resolved in a polymorphic way.

Shadowing Classes

The Shadows modifier will most often be used to reintroduce individual methods, but you can use the Shadows modifier to reintroduce nested classes.

From Chapter 7, we know that a nested class is a class defined within a class. If a parent has a nested class, you can redefine that nested class in a child. Listing 10.8 demonstrates the mechanics of shadowing nested classes.

Listing 10.8 Shadowing nested classes.
 1:  Public Class ParentClass  2:    Protected Class NestedClass  3:      Public Shared Name As String = "Parent.NestedClass"  4:    End Class  5:  6:    Public Shared Function GetName() As String  7:      Return NestedClass.Name  8:    End Function  9:  End Class 10: 11: Public Class ChildClass 12:   Inherits ParentClass 13: 14:   Protected Shadows Class NestedClass 15:     Public Shared Name As String = "Child.NestedClass" 16:   End Class 17: 18:   Public Shared Shadows Function GetName() As String 19:     Return NestedClass.Name 20:   End Function 21: End Class 

ParentClass contains a nested class, NestedClass. ChildClass inherits from ParentClass and reintroduces NestedClass by adding the Shadows modifier to the nested class definition in ChildClass (refer to lines 14 through 16).


Visual BasicR. NET Unleashed
Visual BasicR. NET Unleashed
Year: 2001
Pages: 222

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