Polymorphism and Type Substitution
In the first part of this chapter, inheritance was presented as an effective way to reuse the implementation details of a base class across many derived classes. While reuse of implementations is valuable, another aspect of inheritance is equally important—its support for polymorphic programming.
Every derived class inherits the programming contract that is defined by the public members of its base class. As a result, you can program against any object created from a derived class by using the same programming contract that's defined by the base class. In other words, inheritance provides the ability to program against different types of objects using a single programming contract. This polymorphic programming style is a powerful programming technique because it allows you to write generic, client-side code. That is, the client-side code, which is written against the base class, is also compatible with any of the derived classes, because they all share a common, inherited design. The derived classes are thus plug-compatible from the perspective of the client, making the client's code more applicable to a wider range of situations.
Polymorphism is one of the authors' favorite computer science terms. While precise definitions vary, polymorphism can be envisioned as the notion that an operation (method) supports one or more types (classes). For example, you can write “X + Y”, and this operation will work in .NET whether X and Y are both integers, reals, or strings. Hence the operator “+” is polymorphic, and the code “X + Y” represents polymorphic programming. Expressing this in OOP terms, it might be easier to think of this code as “X.plus(Y)”. At the end of the day, “X.plus(Y)” is more generic because it works in multiple situations.
Let's look at an example of writing generic client-side code based on the principle of polymorphism. This example will use classes within an inheritance hierarchy that has been designed by the Windows Forms team at Microsoft. Figure 5.2 shows some of the more commonly used classes in the Windows Forms framework that provide the implementations for forms and various controls.
Figure 5.2. The inheritance hierarchy of the Windows Forms framework
The hierarchy depicted in Figure 5.2 contains a class named Control that serves as a base class for several other classes. Let's write a method definition called FormatControl against this Control class:
Imports System.Windows.Forms Imports System.Drawing Public Class ControlManager Public Sub FormatControl(ByVal ctrl As Control) '*** generic code using Control class ctrl.BackColor = Color.Blue ctrl.ForeColor = Color.Red End Sub End Class
This implementation of FormatControl is truly generic code. You can call this method and pass a reference to many different types of objects, including Button, CheckBox, TextBox, and Form. When a method such as this one defines a parameter based on the Control class, you can pass an object of any type that inherits either directly or indirectly from the Control class in the inheritance hierarchy.
Suppose you are writing an implementation for an event handler in a form that contains a command button named cmdExecuteTask, a check box named chkDisplayMessage, and a text box named txtMessage. You can achieve polymorphic behavior by writing the following code:
Dim mgr As New ControlManager() mgr.FormatControl(cmdExecuteTask) mgr.FormatControl(chkDisplayMessage) mgr.FormatControl(txtMessage)
Each of these calls is dispatched to the FormatControl method. Even though each call passes a distinct type of object, the FormatControl method responds appropriately because each object “is a” control. The important lesson you should draw from this example is that objects created from a derived class can always be substituted when an instance of the base class is expected.
Method overloading adds yet another dimension to polymorphic programming. For example, you could overload the FormatControl method of the ControlManager class with a more specialized definition in the case of TextBox objects:
Public Class ControlManager Public Sub FormatControl(ByVal txt As TextBox) '*** process object as a text box End Sub Public Sub FormatControl(ByVal ctrl As Control) '*** process other objects as a generic control End Sub End Class
The Visual Basic .NET compiler will dispatch the call to the implementation of FormatControl(TextBox) when it determines that the caller is passing a TextBox reference. It will call FormatControl(Control) when it determines that the Control class is the most-derived class compatible with the type of reference being passed:
Dim mgr As New ControlManager() '*** this call invokes FormatControl(TextBox) mgr.FormatControl(txtMessage) '*** these calls invoke FormatControl(Control) mgr.FormatControl(cmdExecuteTask) mgr.FormatControl(chkDisplayMessage)
As the discussion here reveals, polymorphism is very powerful because it allows you to program in more generic terms and to substitute different compatible implementations for one another. To design, write, and use class definitions in Visual Basic .NET that benefit from polymorphism, however, you must understand a number of additional concepts. The first is the difference between an object type and a reference variable type.
Converting between Types
It's important that you distinguish between the type of object you're programming against and the type of reference you're using to interact with that object. This consideration is especially critical when you are working with classes in an inheritance hierarchy, because you will commonly access derived objects using a base class reference. For example, a TextBox object can be referenced through a variable of type TextBox or a variable of type Control:
Dim textbox1 As TextBox = txtMessage textbox1.Text = "test 1" Dim control1 As Control = txtMessage control1.Text = "test 2"
In the preceding code, the same TextBox object is being accessed through two types of reference variables. The subtle but critical observation here is that an object—and the reference variables used to access that object—can be based on different types. The only requirement is that the reference variable type must be compatible with the object type. A base class reference variable is always compatible with an object created from that base class, or any class that inherits directly or indirectly from that base class. In this example, the control1 reference variable is compatible with a TextBox object because the TextBox class inherits (indirectly) from the Control class.
As you see, inheriting one class from another creates an implicit compatibility between the two types. If you can reference an object using a TextBox reference variable, you are guaranteed that you can also reference that object using a Control reference variable. This is consistent with the is-a rule because a text box “is a” control. Due to this guaranteed compatibility, the Visual Basic .NET compiler allows you to implicitly convert from the TextBox type to the Control type, even with strict type checking enabled. This technique, which is sometimes referred to as up-casting (i.e., casting up the inheritance hierarchy), is always legal.
Trying to convert a base class reference to a derived class reference—that is, down the inheritance hierarchy—is an entirely different matter. Known as down-casting, this technique is not always legal. For example, if you can reference an object using a Control reference variable, you cannot necessarily also reference that object using a TextBox reference variable. While this type of reference might be permitted in some situations, it's definitely not legal in all cases. What if the object is actually a Button and not a TextBox?
When strict type checking is enabled, the Visual Basic .NET compiler will not allow you to implicitly convert down an inheritance hierarchy (e.g., from Control to TextBox). The following code demonstrates how to convert back and forth between Control and TextBox references:
Dim textbox1, textbox2, textbox3 As TextBox Dim control1, control2, control3 As Control '*** (1) compiles with or without Option Strict textbox1 = txtMessage control1 = textbox1 '*** (2) doesn't compile unless Option Strict is disabled control2 = txtMessage textbox2 = control2 '*** error: illegal implicit conversion '*** (3) compiles with or without Option Strict control3 = txtMessage textbox3 = CType(control3, TextBox)
No problem arises if you want to implicitly convert from the TextBox class to the Control class (1). However, the automatic compatibility between these two types works only in a single direction—upward. It is therefore illegal to perform an implicit conversion from a Control reference to a TextBox reference (2). You cannot implicitly convert to a type located downward in the inheritance hierarchy. Therefore, the conversion from Control to TextBox must be made explicitly by using the CType conversion operator (3).
The Visual Basic .NET compiler never worries about the type of the actual object when it decides whether to allow an implicit conversion. Instead, it always relies on the static types of the reference variables being used when deciding whether implicit conversion should be permitted.
Keep in mind that an attempt to convert between types will not always be successful. For example, suppose you attempt to convert a reference variable that is pointing to a CheckBox object into a reference variable of type TextBox:
Dim control1 As Control = chkDisplayMessage Dim textbox1 As TextBox = CType(control1, TextBox)
This code will compile without error because the CType operator is used to perform the conversion explicitly. It will fail at runtime, however, because a CheckBox object is not compatible with the programming contract defined by the TextBox class. In particular, the CLR will determine that the type-cast is illegal and throw an exception. A more detailed discussion of throwing and handling exceptions is deferred until Chapter 9.
If you aren't sure whether an attempt to convert a reference downward to a more-derived type will succeed, you can always perform a runtime test using the TypeOf operator. For example, you can test whether a Control reference variable points to a TextBox-compatible object using the following code:
Public Sub FormatControl(ByVal ctrl As Control) '*** check whether object is a TextBox If TypeOf ctrl Is TextBox Then '*** safe to convert! Dim txt As TextBox = CType(ctrl, TextBox) '*** program against control as TextBox txt.TextAlign = HorizontalAlignment.Center End If End Sub
It's not always necessary to write code that performs this kind of runtime test. You could instead overload the FormatControl method with a more specialized implementation to handle the case of a TextBox object. Nevertheless, sometimes you cannot predict the type of object you'll be dealing with until runtime.
Consider the situation in which you'd like to enumerate through all the controls on a form and perform a specific action only with the text boxes. The form provides a Controls collection that you can enumerate through using a For Each loop, but you cannot determine which controls are TextBox objects until runtime. This scenario offers a perfect example of when you should perform a runtime test using the TypeOf operator:
'*** code in a form's event handler Dim ctrl As Control For Each ctrl In Me.Controls If TypeOf ctrl Is TextBox Then Dim txt As TextBox = CType(ctrl, TextBox) '*** program against control as TextBox txt.TextAlign = HorizontalAlignment.Center End If Next
You have just seen how polymorphism works with a set of classes defined in an existing inheritance hierarchy like the Windows Forms framework. Now it's time to turn your attention to how you can create an inheritance hierarchy of your own and produce the same effect. As part of this discussion, we'll continue with the example started earlier in this chapter, which included the Human base class and the Programmer derived class (see Figure 5.1).