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.
  • 9158

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

  1. You cannot inherit a public class from an abstract class. If you do so, you will see the error shown in Figure 1. 

    MI1.gif
  2. If you do not implement MustOverride members of an abstract class in a derived class, you will get errors as shown in Figure 2. 

    MI2.gif
  3. All MustOverride members of a MustInherit class must be declared as Public.
  4. The members of a class shown in Figure can be used with MustOverride.

    MI3.gif

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.