Home >>VB.Net Built-in Functions >VB.Net Program to demonstrate MustOverride keyword

VB.Net Program to demonstrate MustOverride keyword

Write a VB.Net Program to demonstrate MustOverride keyword

We will create a Sample1 base class here and then inherit the Sample1 class into the Sample2 class. Using the MustOverride keyword, fun() is declared in the Sample1 class method.

Program :

Below is the source code to demonstrate the MustOverride keyword. The program given is compiled and successfully executed.

'VB.net program to demonstrate the MustOverride keyword.


Module Module1
    MustInherit Class Sample1
        MustOverride Sub Fun()
    End Class
    Class Sample2
        Inherits Sample1
        'Here we need to override the Fun() method 
        'otherwise it will generate the error.
        Overrides Sub Fun()
            Console.WriteLine("Override method Fun() called")
        End Sub
    End Class
    Sub Main()
        Dim S As New Sample2()
        S.Fun()
    End Sub
End Module
	
Output:
Override method Fun() called
Explanation:

We created a Module1 module in the program above that comprises two classes, Sample1 and Sample2.

We declared the Fun() method using MustOverride in the Sample1 class, so we have to declare a class using the MustInherit keyword if we declared a method using the MustOverride keyword. Using the Overrides keyword, we then override the Fun() method in the Sample2 class.

Finally, we created a Main() function, which is the program entry point, where we created the Sample2 class object and called the Fun() method, which will print the required message on the console screen.


No Sidebar ads