Function Overriding in Visual Basic .NET

August 29, 2017

You have function named CalculateSalary() in your base class. But you want to changes the function behavior of your derived class. So what you can do is to override base class function in your derived class

Lets see how we can do this
We have People base class code here and you can see the CalculateSalary() method too. You have to use Overrridable keyword in base class function so that you can override the function or property in derived class

Public Class People
    Private strFirstName As String
    Private strLastName As String
    Private dblBasicSalary As Double = 1000


    Public Property FirstName() As String
        Get
            Return strFirstName
        End Get
        Set(value As String)
            strFirstName = value
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return strLastName
        End Get
        Set(value As String)
            strLastName = value
        End Set
    End Property

    Public Overridable Function CalculateSalary() As Double
        Console.WriteLine("This is from super class")
        Return dblBasicSalary
    End Function



End Class

Now you can override the CalculateSalary() method in your derived class called Employee. In the CalculateSalary() method you have to use the keyword Overrides

Public Class Employee
    Inherits People
    Private dblAllowance As Double = 2000
    Public Overrides Function CalculateSalary() As Double

        Console.WriteLine("This is from derived class")
        Return dblAllowance
    End Function
End Class

Now lets create the object in our main module and see the output

Module Module1

    Sub Main()

        Dim p As New Employee()
        p.FirstName = "John"
        p.LastName = "Doe"
        Console.WriteLine(p.CalculateSalary())
        Console.ReadLine()


    End Sub

End Module

Output

This is from derived class
2000

You can see that CalculateSalary() of the derived class executes