MustInherit in VB.NET
A MustInherit keyword applied on a class makes a class abstract class. This article demonstrates how to create an abstract class and use it in VB.NET.
A MustInherit keyword applied on a class makes a class abstract class. An abstract class cannot be instantiated directly. It must be used through its derived classes. The purpose of an abstract class is to enforce must implementations in the base classes.
In the following example, the Human class is an abstract class with three MustOverride members.
MustInherit Class Human
Public MustOverride Sub BodyStructure()
Public MustOverride Property Hands()
Public MustOverride Function MonkeyActions() As Boolean
End Class
When a class is derived from an abstract or MustInherit class, the derived class must override all inherited MustOverride members.
In this below code, class Person is inherited from class Human and overrides all MustOverride members of Human class.
Class Person
Inherits Human
Protected handsCount As Int16
Public Overrides Sub BodyStructure()
End Sub
Public Overrides Property Hands() As Int16
Get
Return Me.handsCount
End Get
Set(ByVal value As Int16)
Me.handsCount = value
End Set
End Property
Public Overrides Function MonkeyActions() As Boolean
Return True
End Function
End Class
Important Rules of MustInherit Classes
- You cannot inherit a public class from an abstract class. If you do so, you will see the error shown in Figure 1.
- If you do not implement MustOverride members of an abstract class in a derived class, you will get errors as shown in Figure 2.
- All MustOverride members of a MustInherit class must be declared as Public.
- The members of a class shown in Figure can be used with MustOverride.