Home > Articles > Programming > Windows Programming

This chapter is from the book

Using Inheritance

The addition of implementation inheritance is probably one of the most eagerly anticipated new features in VB.NET. To support this feature, the VB.NET syntax has been augmented with keywords that specify how a class and its members can be inherited and used in a derived class.

At the class level, the Inherits keyword is used in the class declaration to create a derived class. After the class is inherited, it automatically has all the functionality exposed in the base class and can additionally create new members and override and overload members in the base class. The class acting as the base class does not need to be declared within the current application or even the same namespace. In fact, any .NET class referenced in an assembly in your project can act as a base class, and at run-time the CLR will be able to access its implementation. This includes classes created in other managed languages such as C# and managed VC++.


The CLR supports only single inheritance, which means that a class can be derived from only a single base class. Some languages, such as C++, support multiple inheritance, in which the members from several classes can be inherited in a derived class. However, if you need to bring methods from multiple classes together, you can do so through an inheritance tree. Because an inheritance hierarchy can contain multiple classes, you can create designs in which, for example, class C derives from class B, which derives from class A. In this case, methods implemented by both class A and B are available to be overridden by class C or called from clients using class C.

In addition, classes can be specified with the MustInherit or NotInheritable keywords. By default, all classes are inheritable within their defined scope as defined by the modifiers discussed in the previous section. However, if you want to create a class that acts as an abstract base class, you can do so by adding the MustInherit keyword. An example of using this technique is shown in Listing 4.9 where a partial abstract base class called QuilogyDataAccess is defined.

Listing 4.9 Abstract base class. This listing shows an example abstract base class for a COM+ configured class.

Option Explicit On 
Option Strict Off

Imports System.Data
Imports System.EnterpriseServices

Namespace Quilogy.Education

  Public Interface IQuilogyQuery
    ' Interface used to query 
    Function GetByID(ByVal pID As Long) As DataSet
    Function GetByName(ByVal pName As String) As DataSet
  End Interface

  <Transaction(TransactionOption.Supported), _
   EventTrackingEnabled(True), _
   ConstructionEnabled(Enabled:=True)> _
   Public MustInherit Class QuilogyDataAccess : Inherits ServicedComponent
    Implements IQuilogyQuery

    Protected mstrConnect As String

    Public NotOverridable Overrides Sub Construct(ByVal s As String)
      ' Implements object construction
      mstrConnect = s
    End Sub

    Overrides Function CanBePooled() As Boolean
      ' Default is that the objects will not be pooled
      Return False
    End Function

    Public Overridable Function GetByName( _
     ByVal pName As String) As DataSet _
      Implements IQuilogyQuery.GetByName

    End Function

    Public Overridable Function GetByID(ByVal pId As Long) As DataSet _
     Implements IQuilogyQuery.GetByID

    End Function
  End Class

End Namespace

In this example, the abstract base class QuilogyDataAccess itself inherits from the ServicedComponent Services Framework class to provide access to COM+ transactions (discussed in Chapter 8). The base class also implements the custom interface IQuilogyQuery to provide querying capabilities, as will be discussed later in this chapter.


The Inherits keyword must be placed on a separate line from the Class statement. In this example, the lines are separated using a colon rather than a carriage return-line feed. This syntax has the advantage of making the code more readable, although in most instances I would not recommend using the line separator.

The obvious advantage to being able to create abstract base classes is that you can create a layer of abstraction that allows other developers to reuse your code and at the same time protect that code from direct instantiation. Keep in mind that you must be careful to include all the functionality required and inherit from the appropriate base class when creating abstract base classes because .NET does not support multiple inheritance. Additional functionality can be provided through interfaces, although by definition they provide only the signatures of methods to implement, not the actual implementation.

When a class is used in an inheritance hierarchy, you can place modifiers on the members that determine how they can be used in the derived class. For example the inheritance behavior of methods can be specified using the Overridable, NotOverridable (the default), MustOverride, Overrides, and Overloads keywords. The first three keywords in the list are used in the original declaration of a method to indicate whether the method can or can't be overridden or whether it must be overridden. Note that if you don't specify otherwise, a method cannot be overridden and, when invoked from an instance of a derived class, will execute the implementation in the base class; hence, the genesis of the term implementation inheritance.

For example, the method GetByID in Listing 4.1 uses the Overridable keyword to indicate that the method can be overridden in the derived class. If you use the MustOverride keyword, all you can specify is the method declaration, no implementation. This behavior is essentially like implementing an interface on the class in that it ensures that the derived class will create an implementation for the method.

The Overrides keyword is used in the derived class to indicate methods that have been overridden from the base class. In the earlier example, the Construct procedure was overridden in the base class and so you must explicitly note this in the declaration, as shown in the following example:

Public NotOverridable Overrides Sub Construct(ByVal s As String)
  ' Implements object construction
   mstrConnect = s
End Sub
***Begin Note***


Although it might seem like overkill to require the Overrides keyword—after all, the compiler could simply look to see whether the method name is in the base class and that the signatures match—I like that VB.NET requires it because it forces developers to explicitly note their intention to override a method of the base class rather than simply doing it by accident. At a lower level, the use of the Overridable and NotOverridable keywords allows the JITer to produce more efficient code as well.

Note that overridden methods are just that. When invoked on a derived class, the overridden method in the base class does not run. You can explicitly cause this to happen by using the MyBase object to invoke the overridden method from the derived class.

The Overloads keyword can be used both in a base class and a derived class. In a base class, Overloads is used to create multiple versions of the same method that differ only in their arguments, as you'll see in the following discussion. This allows a client to select which implementation they wish to call at design-time. A typical use for overloaded methods in a base class is to create varying versions of the class constructor, as will be shown later. In VS.NET, overloaded methods are shown by a list of possible signatures in the autocompletion window. In a derived class, Overloads is used to add additional method signatures available to the client. Depending on which one the client chooses, the actual code might execute either in the base class or the derived class.


The Overloads keyword is not required when overloading methods within a class but it is required when a derived class overloads a method from the base class. However, if one overloaded method in a class has the Overloads keyword, then they all must.

Finally, the Shadows keyword can be used in a derived class to reuse and redeclare a member from the base class. In other words, even if the base class does not specify that an existing method can be overridden, you can declare a method of the same name in the derived class with the Shadows modifier in order to use the name. In this event, the shadowed method from the base class is not overloaded but becomes unavailable in the derived class and all its descendants. This can be useful when you want to hide all the overloaded members from the base class and expose only one signature for the member to clients of your class.


If a method specifies neither Shadows nor Overloads then the VB .NET compiler will issue a warning but Shadows will be assumed. However, it is recommended to always explicitly use Shadows when that is your intent.

Using Polymorphism

In addition to the ability to reuse the implementation of a class in derived classes, one of the other primary benefits to using inheritance is polymorphism. Creating an inheritance hierarchy implicitly means that the derived classes have a "is a" relationship with the base class and therefore, they can be treated polymorphically. For example, as discussed previously, if a Velociraptor class is derived from the Theropod class, any client code that is designed to work with the Theropod class will also work with the Velociraptor class since Velociraptor is a Theropod. Consider the following method signature that accepts an argument of type Theropod:

Public Sub PrintDinosaur(ByRef oTheropod as Theropod)

Because Velociraptor is derived from Theropod, a client application can instantiate a Velociraptor object and pass it to this method as follows:

Dim oVec as New Velociraptor

VB.NET will allow this behavior only if the Option Strict statement is set to Off. If it is on, however, you must first use the CType function to convert the reference oVec to Theropod as follows:

PrintDinosaur(CType(oVec, Theropod))

Obviously, by writing code that works against your base classes, you'll end up being able to reuse the code to perform work on derived objects as well.

Creating and Using Shared Members

One of the biggest changes in VB.NET that supports true OO programming and that works hand-in-hand with inheritance is the use of shared or static members (sometimes called class members). As the name implies, shared members are methods, properties, fields, and events that are shared between all instances of the class and any derived classes for which they are defined. This allows all objects created with the class to access the same data (in the case of properties and fields) and implementation (in the case of methods), and to receive the same fired event (in the case of events).

To mark a member as shared, you simply use the Shared keyword on either Public or Private members. For example, consider the Count field of the Instructors class discussed earlier. Obviously, this kind of data is a good candidate for sharing among all instances of the class because it should be automatically updated for all instances when any one instance adds a new instructor. To implement the shared field, you would simply redefine it at the class level as follows:

Public Shared ReadOnly Count As Integer

However, by making the field read-only, other methods that are not shared within the class—such as Add—would not be able to increment the Count. Because of this limitation, you could instead create Count as a read-only instance property and store the internal value of the count as a shared private variable as follows:

Private Shared mCount As Integer

ReadOnly Property Count() As Integer
    Return mCount
  End Get
End Property

In this way, both the shared constructor and other shared and instance methods have access to mCount.

When using shared members, you must keep in mind that within a shared member you cannot access data that is particular to an instance. In other words, you cannot manipulate variables, properties, or call methods that are not also marked as shared. However, the reverse is not true, so you can safely increment the mCount shared variable from within a virtual method such as Add.

Public Function Add() As Integer
  ' Perform the transaction
  mCount += 1
End Function

In addition, shared methods and properties cannot be overridden in descendant classes, although they can be overloaded both in the base class and in any derived class. This behavior is the default so that any shared method is the only implementation available for the base class and all its descendants. However, a class can extend the implementation by creating overloaded members that accept different arguments.


If you declare a variable as shared in the base class and declare the same variable in a derived class, regardless of the modifier, the runtime will treat them as two entirely separate entities within their respective scopes. As a result, any code in the derived class that refers to the name will reference the variable defined in the derived class and result in the obfuscation of the shared variable. Similarly, any code in the base class will modify only the shared variable.

To summarize, shared members are useful when all instances of a class will share the same data or when the class has a standard set of methods that will operate identically across all instances of the class and any derived classes.

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.


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.


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.


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.


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


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


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.


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.


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