How to use inheritance in Visual Basic 2005 or in Visual Basic .NET (307222)



The information in this article applies to:

  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

This article was previously published under Q307222
For a Microsoft Visual C# .NET version of this article, see 307205.

SUMMARY

Inheritance is an important object-oriented concept. It allows you to build a hierarchy of related classes and to reuse functionality defined in existing classes.

In this article, you will learn how to use inheritance in Microsoft Visual Basic 2005 or in Microsoft Visual Basic .NET. You will define a base class that contains fields and methods for a generic bank account. You will then define a derived class that represents a particular kind of bank account. The derived class will inherit members from the base class, override selective members, and add new members for that type of account.

Requirements

Prior knowledge required:
  • Visual Basic 2005 or Visual Basic .NET syntax
  • Object-oriented concepts

Create a new console application

  1. Start Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET, and create a new Visual Basic console application project named UseInheritance on your local computer.
  2. On the Project menu, click Add Class.
  3. In the Add New Item dialog box, type Account.vb in the Name field. Click Open.

    Note In Visual Studio 2005, click Add instead of Open.
  4. Visual Studio .NET displays the file Account.vb.
  5. Save the project.

Create an abstract base class

  1. Add the MustInherit modifier to the Account class, to make Account an abstract class:
    Public MustInherit Class Account
    
    End Class
    					

Write code for the base class

  1. Add two fields to the Account class:
    Private Name As String       ' Only accessible in base class
    Protected Balance As Double  ' Accessible in base class and derived class
  2. Add a constructor to initialize these fields:
    Public Sub New(ByVal Nm As String, ByVal Bal As Double)
       Name = Nm
       Balance = Bal
    End Sub 
  3. Add the following methods to the class. The Overridable keyword means these methods can be overridden in derived classes:
    Public Overridable Sub Credit(ByVal Amount As Double)
       Balance += Amount
    End Sub
    
    Public Overridable Sub Debit(ByVal Amount As Double)
       Balance -= Amount
    End Sub
    
    Public Overridable Sub Display()
       Console.WriteLine("Name=" & Name & ", " & "Balance=" & Balance)
    End Sub
  4. Add the following method to the class. Because this method is not marked as Overridable, it cannot be overridden in derived classes. This method provides the capability to change the name of the account holder.
    Public Sub ChangeName(ByVal newName As String)
       Name = newName
    End Sub
  5. Add the following method to the class. The MustOverride keyword means this method must be overridden in derived classes:
    Public MustOverride Function CalculateBankCharge() As Double

Create a derived class

  1. From the Project menu, click Add Class.
  2. In the Add New Item dialog box, type SavingsAccount.vb in the Name field. Click Open.
  3. Visual Studio .NET displays the file SavingsAccount.vb.
  4. Change the SavingsAccount class definition as follows, so that SavingsAccount inherits from Account (note that the Inherits keyword must appear on a new line):
    Public Class SavingsAccount 
       Inherits Account
    
    End Class

Write code for the derived class

  1. Add a field to the SavingsAccount class:
    Private MinBalance As Double  ' If the balance drops below MinBalance, 
                                  ' the bank will charge a fee on the account
  2. Add a constructor as follows, to initialize the fields in the base class and in this class:
    Public Sub New(ByVal Nm  As String, _
                   ByVal Bal As Double, _
                   ByVal Min As Double)
       MyBase.New(Nm, Bal)        ' Call base-class constructor first
       MinBalance = Min           ' Then initialize fields in this class
    End Sub
  3. Add the following methods to the SavingsAccount class. These methods override the Overridable methods inherited from the base class:
    Public Overrides Sub Debit(Amount As Double)
       If Amount <= Balance Then  ' Use balance, inherited from base class
          MyBase.Debit(Amount)    ' Call Debit, inherited from base class
       End If
    End Sub
    
    Public Overrides Sub Display()
       MyBase.Display()           ' Call Display, inherited from base class
       Console.WriteLine("$5 charge if balance goes below $" & MinBalance)
    End Sub
  4. You must override all MustOverride methods from the base class. Add the following method to the SavingsAccount class:
    Public Overrides Function CalculateBankCharge() As Double
       If Balance < MinBalance Then
          Return 5.0
       Else
          Return 0.0
       End If
    End Function

Verify that it works

  1. Display the code for Module1.vb in the Code View window.
  2. In the Main method, create a SavingsAccount object as follows:
    Dim sa As SavingsAccount = New SavingsAccount("Freda Smith", 100.00, 25)
    sa.Display()
  3. Add the following code to call Public methods in SavingsAccount or Account:
    sa.Credit(100)
    sa.Debit(180)
    sa.ChangeName("Freda Jones")
    sa.Display()
    Console.WriteLine("Bank charge: $" & sa.CalculateBankCharge())
    					
  4. Build the application.
  5. From the Debug menu, click Start Without Debugging to run the application. The application displays the following information on the console:

    Name=Freda Smith, balance=100
    $5 charge if balance goes below $25
    Name=Freda Jones, balance=20
    $5 charge if balance goes below $25
    Bank charge: $5
    						

  6. Run the application again, but this time use the debugger. Set a breakpoint at the start of the Main method and select Start from the Debug menu. Step into each statement and observe which methods are called during the application.

Modification Type:MinorLast Reviewed:10/3/2006
Keywords:kbvs2005applies kbvs2005swept kbHOWTOmaster KB307222 kbAudDeveloper