Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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).

NOTE

Generally, polymorphism is implemented using a virtual methods table—an array of method pointers—and 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 call—not shown—and 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.

NOTE

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.

NOTE

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

TIP

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 modifier—placed in the same location as the Overrides or Overridable modifiers—to 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).

  • + Share This
  • 🔖 Save To Your Account

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