Relevant Codes (by Anshoo Arora)

A Test Development Resource for HP QuickTest Professional.

Inheritance in VB.NET

by Anshoo Arora on August 10, 2009

In OOP, Class Inheritance has been one of the most important topics and it has been around since 1967 The idea behind class inheritance is to enable the inheriting (derived) classes use attributes of the base classes. This enables programmers to reuse the code by having derived classes share the functionality of their base classes making maintenance easier.

Below is an example of using Class Inheritance in VB.NET. Base Class MyRoom:

Option Explicit On
Option Strict On
Imports System
 
'* Base Class clsMyRoom
Public Class clsMyRoom
 
    Private intWidth As Integer
    Private intLength As Integer
 
    ' constructor that takes 2 integers roomWidth and roomLength
    Public Sub New(ByVal rmWidth As Integer, ByVal rmLength As Integer)
        Me.intWidth = rmWidth
        Me.intLength = rmLength
    End Sub
 
    ' creates my room
    Public Sub CreateItem()
        Console.WriteLine("Creating item {0} units wide and {1} units long.", intWidth, intLength)
    End Sub
 
End Class

Derived Class MyDesk (inherits MyRoom):

'* Child (derived) Class clsMyDesk
'* Uses the Inherits Keyword
Public Class clsMyDesk : Inherits clsMyRoom
 
    Private sColor As String
    Private sShape As String
 
    ' constructor that takes 2 strings (color, shape) and 2 integers (width, length)
    Public Sub New(ByVal dskColor As String, ByVal dskShape As String,_
                   ByVal dskWidth As Integer, ByVal dskLength As Integer)
     ' MyBase invokes the method of the Base Class
        MyBase.New(dskWidth, dskLength)
        Me.sColor = dskColor
        Me.sShape = dskShape
    End Sub
 
    ' creates my desk
    Public Shadows Sub CreateItem()
        ' MyBase points to clsMyRoom
        MyBase.CreateItem()
        Console.WriteLine("Desk will be in {0} color and have a {1} shape.", sColor, sShape)
    End Sub
 
End Class

Module:

Module Module1
    Sub Main()
        Dim myRoom As New clsMyRoom(20, 25)
        myRoom.CreateItem()
 
        Dim myDesk As New clsMyDesk("red", "rectangular", 2, 4)
        myDesk.CreateItem()
 
        System.Console.Read()
    End Sub
End Module

Output:

Creating item 20 units wide and 25 units long.                ' myRoom.CreateItem()
 
Creating item 2 units wide and 4 units long.                  ' myDesk.CreateItem()
Desk will be in red color and have a rectangular shape.


Further reading

  1. Jessy Liberty: Learning Visual Basic .NET (O’Reilly & Associates)
  2. Inheritance in VB.NET
  3. Inheritance (computer science)
  4. Type Polymorphism

If you have any questions, please ask them in the comments section. If your query is confidential, please use the Contact Form to send me an e-mail instead.

Leave a Comment

Previous post:

Next post: