Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Classes and Objects

Inheritance, Polymorphism and Interfaces

Learn inheritance in Visual Basic .NET: Inherits, MyBase, Overridable and Overrides, MustInherit and MustOverride, NotInheritable, polymorphism, Implements, and how to choose between abstract classes and interfaces.

Inheritance lets a new class reuse and extend an existing one. A Dog is an Animal, so it gets everything an animal has and adds its own behavior. Polymorphism means code written for Animal works with any subclass, each reacting in its own way. Interfaces describe what a type can do without saying how, so unrelated classes can be used through one common contract. Listings are VB.NET (read-only); runnable C# stand-ins show the same behavior.

Inherits and MyBase

A class names its base class with Inherits. VB allows single inheritance: one base class only (but many interfaces).

VB
Public Class Animal
    Public Property Name As String

    Public Sub New(name As String)
        Me.Name = name
    End Sub

    Public Overridable Function Speak() As String
        Return "..."
    End Function
End Class

Public Class Dog
    Inherits Animal

    Public Sub New(name As String)
        MyBase.New(name)              ' call the base constructor first
    End Sub

    Public Overrides Function Speak() As String
        Return $"{Name} says Woof"
    End Function
End Class

Public Class Cat
    Inherits Animal

    Public Sub New(name As String)
        MyBase.New(name)
    End Sub

    Public Overrides Function Speak() As String
        Return MyBase.Speak() & " " & Name & " says Meow"
    End Function
End Class

Key words:

  • Overridable: the base class allows subclasses to replace this member. Without it, the member cannot be overridden (the opposite of Java and the same as C#'s virtual).
  • Overrides: the subclass replaces the base member. The signatures must match.
  • MyBase: refers to the base class, for constructors and for calling the original implementation.
  • NotOverridable: seals an override so subclasses below cannot change it again.
  • Shadows: hides a base member by name without overriding. It breaks polymorphism, so avoid it.

If the base class has no parameterless constructor, every subclass constructor must call a base constructor explicitly with MyBase.New(...) as its first statement.

Polymorphism

A variable of a base type can refer to any subclass object. A call to an Overridable method runs the actual object's version at run time:

VB
Dim zoo As New List(Of Animal) From {
    New Dog("Rex"),
    New Cat("Tom"),
    New Animal("Generic")
}

For Each a As Animal In zoo
    Console.WriteLine(a.Speak())
Next

The loop never asks which kind of animal it has: new subclasses plug in without changing this code. This is the main payoff of inheritance.

C# Stand-in (C#): virtual methods and polymorphism

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

MustInherit and MustOverride: abstract classes

A class marked MustInherit cannot be instantiated; it exists only to be a base. Members marked MustOverride have no body and must be implemented by concrete subclasses:

VB
Public MustInherit Class Shape
    Public MustOverride Function Area() As Double

    Public Function Describe() As String      ' shared, finished behavior
        Return $"{Me.GetType().Name} with area {Area():F2}"
    End Function
End Class

Public Class Circle
    Inherits Shape
    Private ReadOnly _r As Double
    Public Sub New(r As Double)
        _r = r
    End Sub
    Public Overrides Function Area() As Double
        Return Math.PI * _r * _r
    End Function
End Class

Dim s As New Shape() is a compile error. NotInheritable is the opposite: it forbids subclasses (like C#'s sealed), and String is such a class.

Interfaces

An interface lists members without bodies. A class that Implements it must provide every member. Interface names start with I by convention. A class can implement any number of interfaces.

VB
Public Interface IPayable
    ReadOnly Property Amount As Decimal
    Function Pay() As String
End Interface

Public Interface IPrintable
    Sub Print()
End Interface

Public Class Invoice
    Implements IPayable, IPrintable

    Public ReadOnly Property Amount As Decimal Implements IPayable.Amount
        Get
            Return 120D
        End Get
    End Property

    Public Function Pay() As String Implements IPayable.Pay
        Return $"Paid {Amount:C}"
    End Function

    Public Sub Print() Implements IPrintable.Print
        Console.WriteLine("Invoice printed")
    End Sub
End Class

VB uses an explicit Implements InterfaceName.MemberName clause on each member. That also means the member can have a different name from the interface member, and the same method can implement two interface members. Interfaces can inherit from other interfaces with Inherits.

C# Stand-in (C#): abstract class and interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Abstract class or interface?

Question Abstract class (MustInherit) Interface
Share real code and state? Yes No (only contracts; limited default members)
Number a class can use One Many
Models an "is-a" family with shared parts a "can-do" capability
Changing it later Adding a concrete member is safe Adding a member breaks implementers

Rule of thumb: start with an interface when unrelated classes must be used the same way (IComparable, IDisposable, IEnumerable); use an abstract class when related classes share implementation.

Checking and casting types

TypeOf x Is Dog tests the runtime type, and DirectCast or TryCast convert (see Option Strict and Conversions). A type test against an interface works too: If TypeOf item Is IPrintable Then ....

Common mistakes

  • Forgetting Overridable on the base member and then getting error BC31086 when you write Overrides.
  • Not calling MyBase.New(...) when the base has no default constructor.
  • Using Shadows and then wondering why a base-typed variable calls the old version.
  • Building deep inheritance chains. Prefer composition (a class holding another object) when "is-a" is not clearly true.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which keyword must the base class put on a method so subclasses can override it?

    Overridable (virtual) allows replacement; the subclass then uses Overrides.
  2. 2. What does MustInherit mean for a class?

    A MustInherit class is abstract: you create objects of subclasses, not of the class itself.
  3. 3. How many base classes can a VB.NET class have?

    VB.NET has single inheritance, but a class can implement many interfaces.
  4. 4. How does a class declare that a member implements an interface member?

    VB requires the explicit Implements clause naming the interface member.
  5. 5. A variable of type Animal holds a Dog. Which version of Speak runs for an Overridable method?

    Overridable methods are dispatched on the object's real type at run time.

Summary

  • Inherits gives single inheritance; MyBase reaches the base class; Overridable/Overrides enable polymorphism.
  • MustInherit/MustOverride create abstract classes; NotInheritable and NotOverridable stop further extension.
  • Interfaces define contracts; classes bind to them with Implements Interface.Member.
  • Choose interfaces for capabilities and abstract classes for shared implementation; prefer composition over deep hierarchies.

Next: Events and Delegates