ProgrammingVB.NET Developer

How to implement a class hierarchy with inheritance and polymorphism in Visual Basic? Describe how to properly use virtual methods (Overridable/Overrides), and provide a code example with a base and derived class.

Pass interviews with Hintsage AI assistant

Answer

In Visual Basic .NET, inheritance is implemented using the Inherits keyword. It allows creating class hierarchies that implement common and overridable methods and properties.

To support polymorphism, methods in the base class are declared with the Overridable modifier, while in the derived class they are overridden using Overrides. The NotOverridable modifier is used to prevent further overriding.

Example:

' Base class Animal with a virtual method Public Class Animal Public Overridable Sub Speak() Console.WriteLine("The animal makes a sound.") End Sub End Class ' Derived class Dog overrides Speak Public Class Dog Inherits Animal Public Overrides Sub Speak() Console.WriteLine("The dog barks.") End Sub End Class Sub Main() Dim a As Animal = New Dog() a.Speak() ' Outputs: The dog barks. End Sub

Trick Question

Q: Can you override methods in Visual Basic .NET that are not declared as Overridable/Abstract in the base class?

A: No. Only methods marked as Overridable or declared via an interface/abstraction can be overridden when inheriting. Trying to use Overrides for a regular method will cause a compilation error.

' Error: Public Class A Public Sub Foo() End Sub End Class Public Class B Inherits A Public Overrides Sub Foo() ' Compilation error End Sub End Class

Story

1. In a real project related to microservices architecture, a new team member declared a virtual method as a regular one (without Overridable) in the base controller class. Later, another developer tried to override this method for special handling. As a result, code duplication and bugs occurred, as the parent implementation was always called, despite the presence of the method in the derived class.


Story

2. Insufficient architectural planning and a lack of use of polymorphism led to hundreds of lines of excessive code: when a new derived class needed to be added, a large part of the base class method had to be rewritten instead of just implementing the required Override. This complicated maintenance and support.


Story

3. An incident in a corporate application: during migration to .NET Core, a developer marked a method as Overridable but mistakenly did not add Implements for the interface. As a result, ambiguity in method resolution in the inheritance hierarchy was discovered, leading to issues when called through an interface reference, resulting in non-functional features.