Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
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++.

NOTE

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.

NOTE

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***

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.

NOTE

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.

TIP

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
PrintDinosaur(oVec)

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

CAUTION

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.

  • + Share This
  • 🔖 Save To Your Account