VB.NET Inherits Keyword

The VB.NET programming language

How can you use the Inherits keyword in your VB.NET program? With Inherits, one class can inherit from another class. This means it gains all the fields and procedures from the parent class.

Example

Note

Let's begin by looking at Class A: this class contains a field (_value) as well as a Sub (Display()). Next, Class B and Class C both use the Inherits keyword and are derived from Class A. They provide their own constructors (New). You can see the New B() and New C() will do slightly different things when called.

This VB example program shows how to use the Inherits keyword.

Program that uses Inherits keyword [VB.NET]

Class A
    Public _value As Integer

    Public Sub Display()
	Console.WriteLine(_value)
    End Sub
End Class

Class B : Inherits A
    Public Sub New(ByVal value As Integer)
	MyBase._value = value
    End Sub
End Class

Class C : Inherits A
    Public Sub New(ByVal value As Integer)
	MyBase._value = value * 2
    End Sub
End Class

Module Module1
    Sub Main()
	Dim b As B = New B(5)
	b.Display()

	Dim c As C = New C(5)
	c.Display()
    End Sub
End Module

Output

5
10

MyBase composite name. In programming languages, a name such as "MyBase._value" is called a composite name. In VB.NET, this means we are accessing the base class (A) and the field on the base class (_value). This eliminates any ambiguity between fields that might occur.

Call base Sub. You can see in the example program that the Display Sub is defined only on Class A. However, Class B and Class C inherit this Sub as well as the field. This means that when b.Display() and c.Display() are called, the A.Display Sub is invoked.

Interfaces

Illustration

One option to consider instead of the Inherits keyword is the usage of Interfaces. You can use the Implements keyword to specify an Interface. Conceptually, an Interface is a contract, a set of demands that compliant types will adhere to. A base class, meanwhile, is a core template of data and functionality that can be used to build upon.

Interface Example

Summary

We examined a simple program that uses the Inherits keyword to derive classes from a base class. With Inherits in the VB.NET language, we gain the ability to implement complex object models that can very closely represent, in a declarative way, a type framework which we can use to solve problems.

VB.NET Tutorials
.NET