Home > Articles > Business & Management > Finance & Investing

This chapter is from the book

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.

Polymorphism

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.

Poly-whatism?

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.

05fig02.gifFigure 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).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020