Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

What Is Inheritance?

Recall that classes contain fields, properties, events, and methods. Inheritance implies at least two classes: one class plays the role of parent and the second class plays the role of child. (Occasionally we refer to sibling classes, those descended from the same parent. Seldom do we refer to a grandparent; generally when we discuss any ancestor beyond an immediate parent, we use the term ancestor.)


A parent class is also referred to as a superclass, and a child class is also referred to as a subclass.

Remember that the same class can be parent or child, depending on your perspective. For example, you are the parent of your children but the child of your parents. If you combine the parent-child relationship with the interchangeable parent/superclass and child/subclass vernacular, and mix in a few people talking about classes and objects as if they were the same things, a discussion can become quite confusing.

We can dispel one concept completely. Classes are not objects. A class is a definition and an object is an instance of a definition. If a discussion becomes confused, consider sticking to one pair of terms, parent and child, and using class to mean only definition and object to mean only instance.

When we say inheritance in Visual Basic .NET, we mean that a child gets a copy of everything found in a parent plus anything we add to that child. Technically, a child gets a copy of the data and access to a methods table, but for simplicity we think of child classes as getting their own copy of everything. This does not mean that a child can directly access every member inherited from the parent; access rules still apply. The child gets a copy of everything, but can only directly access public, protected, and friend members of a parent. Because private members represent implementation details, a child class is usually interacting with private members indirectly via public, protected, or friend members.

The simplest representation of the parent-child relationship is that of union from mathematics (see Figure 10.1). (I always wondered where it would be necessary to use those union and intersection diagrams from elementary school.)

Figure 10.1 Inheritance can be appropriately represented as the union of parent and child.

A reasonable representation of inheritance access is represented by an intersection relationship (see Figure 10.2).

Figure 10.2 Inheritance access is represented by an intersection relationship.

The child class shown in Figure 10.1 is a replica, plus something additional, of its parent. Information hiding and complexity management is represented by Figure 10.2. From the child-as-consumer perspective, the child in Figure 10.2 is only concerned with the members not in the Private section of the parent class.

Basic Inheritance Statement

Fortunately the grammatical complexity of inheritance relationships is miniscule. Given two classes, one playing parent and the other child, all you need to do is add a single statement to indicate inheritance in Visual Basic .NET. Listing 10.1 demonstrates the statement for indicating inheritance.

Listing 10.1 The simplest inheritance relationship.

Public Class Parent

End Class

Public Class Child
 Inherits Parent
End Class

From the listing you can see that Inherits Parent is all that we must add to indicate inheritance of child from parent. The grammar is the easy part. Choosing what to expose in a parent and what to add to a child is the very subjective part of object-oriented programming that trips some programmers up.

There are no good general rules dictating what to inherit or how many members to add to a child class or override from a parent class. What are available are platitudes like "subjective good taste" and "reasonable and sufficient." What these statements mean is that inheritance is like flying or surgery: You have to land dozens of times or carve up numerous cadavers before you fly with passengers or operate on real people.

Having read thousands of pages and written tens of thousands of lines of code spanning two decades, I can tell you that I am seldom happy with my first attempt. The rest of this book provides many examples of inheritance; here I can offer a few basic guidelines that will get you started:

  • Make methods protected and virtual unless you are reasonably sure they should not be.

  • When you have a class that works and needs new behavior, create a child class and add the behavior to the child. You will not break existing code by modifying an existing class. You will have the old and new behavior and two classes to draw from.

  • When defining reference parameters, define parameters to be parents reasonably high up in the architecture. You can always pass an instance of a child and typecast the parameter.

  • Keep the number of public members to about a half-dozen.

  • Keep methods and property methods very short and singular.

  • Name methods using good verbs and properties using good nouns. Don't scrimp by using nonstandard abbreviations; use whole words.

  • Try to maintain a balance between breadth and depth in your architecture, not too deep or wide.

  • Refactor. Refactor. Refactor.

For every rule in the bulleted list, there is an exception, almost. In a large number of cases these rules will keep you in safe territory. The only one that shouldn't be optional is refactoring.

Inheritance by Example

The best way to gain experience with inheritance is to write and read a lot of code that involves inheritance. If most of your programming experience has been in Visual Basic—not in languages like C++, Java, and Object Pascal—you have not had much experience in defining inheritance relationships. The code in this book uses inheritance a lot, and several examples of inheritance follow in this section. Each example is followed by a brief synopsis. Consider this code:

Public Class Form1
 Inherits System.Windows.Forms.Form
End Class

Every form in a Windows applications inherits from the base form class defined in System.Windows.Forms. You will see this statement every time you design a new form in a Windows application:

Public Class WebForm1
 Inherits System.Web.UI.page
End Class

This fragment demonstrates a Web form that inherits from System.Web.UI.page. When you create an ASP.NET Web application in Visual Basic .NET, your Web forms will inherit from the page class.

Here's another type of inheritance example:

Private Class RedLight
 Inherits Light
End Class

The Private nested class RedLight inherits from Light. This is an example from Chapter 7 that demonstrates how to implement a private nested class and inherit from it.

Look at the next example:

Public Class IndexedException
 Inherits ApplicationException
End Class

When you extend the exception architecture, you can inherit from ApplicationException to implement custom exception classes. (This is also an example from Chapter 7.)

As demonstrated, the inheritance statement is always the same. The exact details about a parent class you want to modify and extend in a child class determine what code you will write in that child.

Implementing Properties, Events, and Methods in the Code Editor

When you inherit from a class, the Method Name combo box at the top-right side of the code editor will contain a hierarchical sublist of properties, events, and methods that can be implemented in a child class. For example, when you add a new form to a Windows application, you can pick from a list of members that are inherited, a list of overridable members, and a list of events.

Applying the behavior of the code editor to responses to the inputs during design time, if you double-click on a form, you will get a generated event handler for the Load event. The empty event handler represents an event handler for the base class event Load (see Figure 10.3).

Private Sub Form1_Load(ByVal sender As Object, _
 ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Figure 10.3 Events are organized in the code editor by (Base Class Events) in the Class Name list, shown open in the figure.

However, if you select the (Overrides) sublist, you can override the method that invokes the Load event.

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)

End Sub


If you have Form_Load and OnLoad implemented in the same class, Form_Load will only be called if you call the base class method or raise the event yourself.

The event handler is related to the method that raises the event. In the Form parent class, it is the OnLoad event that raises the event your code is responding to in Form1_Load. Because events are not polymorphic directly, events can be made polymorphic indirectly by raising them via a method that can be overridden. (Refer to the section "Polymorphism" later in this chapter.)

If you want to respond to the OnLoad event, implement the Form_Load event handler. If you want to modify the OnLoad response in a subclass, you can override the OnLoad subroutine in a child. The default OnLoad method raises the event. An overridden OnLoad method can elect to perform the default behavior—that is, raise the event—or some new behavior.

Using MyBase

If you override a parent behavior in a child class, you can then call the parent behavior, or not call the parent behavior and perform some additional operation before or after invoking the parent behavior.

You only need to override a parent method if you want to extend or replace the parent method. Applied to our OnLoad versus Form_Load scenario, only implement OnLoad if the default behavior that raises the event is insufficient.


MyBase is a keyword like Me. Whereas Me refers to self, MyBase refers to the immediate ancestor of self.

If you want to perform the behavior of the parent, call MyBase.parentmethod. For example, MyBase.OnLoad will call the parent class behavior in the OnLoad method, and you can add other behavior before or after calling the parent behavior. An OnLoad method that produces behavior identical to the default Form.OnLoad method follows:

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
End Sub

Overloading the Form.OnLoad Method

Suppose you wanted to add an entry into the Windows Event Log (see Figure 10.4) during testing every time a form was loaded. You could overload the OnLoad method and add the code to write the event log entry after the default behavior is performed, as demonstrated in Listing 10.2.


If you want to perform some behavior on an event, implement an event handler. If you want to change the way, order, or timing of the event handler, overload the On... method that raises the event.

Listing 10.2 By convention, events are raised by methods prefixed with On; overload these methods to alter the behavior, order, or timing of an event invocation.

1: Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
2:  MyBase.OnLoad
3:  EventLog.WriteEntry("Form1", "OnLoad method called")
4: End Sub

Line 2 calls the parent class's method, which raises the Load event, and line 3 performs the additional behavior of adding an entry to the Application event log (shown in Figure 10.4).

Figure 10.4 A logged application event using the Shared method EventLog. WriteEntry.

Single Inheritance Versus Multiple Inheritance

Visual Basic .NET does not support multiple class inheritance. Visual Basic .NET does support multiple interface derivation (discussed later), but then you are not inheriting the members. When a class agrees to implement multiple interfaces, the contract between class and interface is that the class implements all members of all interfaces.


Multiple inheritance is demonstrated by a class that has more than one parent class. For example, you have physical attributes that can be described as having been inherited from mother and father.

Visual Basic .NET supports single class inheritance and multiple interface inheritance.

You will encounter Inherits statements that look like multiple inheritance but are actually indicating interface inheritance. That is, an interface can be described as an aggregate of more than one interface using the Inherits keyword (refer to Listing 10.3).

Listing 10.3 Multiple interface inheritance is supported in Visual Basic .NET.

Public Interface I1
End Interface

Public Interface I2
End Interface

Public Interface I3
 Inherits I1, I2
End Interface

Listing 10.3 indicates that Interface I3 inherits the interface described by I2 and I1. I3 does not get the members of I2 and I3; rather I3 defines a new interface that is made up of I1's and I2's interfaces. Classes that implement I3 must implement all of I1 and I2.

Visual Basic .NET supports multiple interface inheritance but only single class inheritance. A new interface that inherits multiple interfaces is perfectly valid. Interface I3 in the preceding example demonstrates multiple interface inheritance.

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