What Is Inheritance?


Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 10.  Inheritance and Polymorphism

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 Basicnot in languages like C++, Java, and Object Pascalyou 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).

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


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

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 behaviorthat is, raise the eventor 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)   MyBase.OnLoad 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.

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



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

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.


Visual BasicR. NET Unleashed
Visual BasicR. NET Unleashed
Year: 2001
Pages: 222

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net