VB.Net program to call base class and derived class overridable method using base class reference

Here, we are going to learn how to call base class and derived class overridable method using base class reference in VB.Net?
Submitted by Nidhi, on December 28, 2020 [Last updated : March 06, 2023]

Calling base class and derived class overridable method using base class reference in VB.Net

Here, we will create a base class Sample1 and then inherit Sample1 class into Sample2 class and override the method of Sample1 class into Sample2 class. After that, we called the base and derived class method using base class reference.

Program/Source Code:

The source code to call base class and derived class overridable method using base class reference is given below. The given program is compiled and executed successfully.

VB.Net code to call base class and derived class overridable method using base class reference

'VB.net program to call base class and derived class 
'overridable method using base class reference.

Module Module1
    Class Sample1
        Overridable Sub Fun()
            Console.WriteLine("Sample1.Fun() called")
        End Sub
    End Class

    Class Sample2
        Inherits Sample1
        Overrides Sub Fun()
            Console.WriteLine("Sample2.Fun() called")
        End Sub
    End Class

    Sub Main()
        Dim S As Sample1 = New Sample1()
        S.Fun()

        S = New Sample2()
        S.Fun()
    End Sub
End Module

Output:

Sample1.Fun() called
Sample2.Fun() called
Press any key to continue . . .

Explanation:

In the above program, we created a module Module1 that contains two classes Sample1 and Sample2. In the Sample1 class, we created method Fun(), which is declared as overridable. Then we inherited Sample1 class into the Sample2 class. In the Sample2 class, we override the Fun() method using the Overrides keyword.

At last, we created a Main() function, which is the entry point for the program, here we created the reference of Sample1 class and then initialized the reference by Sample1 and Sample2 object and called fun() method and print the appropriate message on the console screen.

VB.Net Basic Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.