ProgrammingVB.NET Developer

How does the inheritance mechanism work in Visual Basic .NET, and how can it be managed properly to ensure code flexibility and safety?

Pass interviews with Hintsage AI assistant

Answer

In Visual Basic .NET, inheritance is implemented using the Inherits keyword, which allows creating new classes based on existing ones, inheriting their properties and methods. This enables code reuse and extends functionality without duplication.

When inheriting, it is important to:

  • Mark members of the base class with the Protected modifier or use Overridable/Overrides for methods that should be overridden.
  • Use the MustInherit keyword for abstract classes and NotInheritable to prohibit inheritance.

Example:

' Abstract class Public MustInherit Class Animal Public MustOverride Sub MakeSound() End Class ' Derived class Public Class Dog Inherits Animal Public Overrides Sub MakeSound() Console.WriteLine("Woof!") End Sub End Class

Features:

  • VB.NET allows only single inheritance of classes.
  • Interfaces are implemented using the Implements keyword.

Trick Question

Can a class inherit from multiple classes in Visual Basic .NET?

Wrong answer: Yes, possible through commas (or through interfaces).

Correct answer: No, Visual Basic .NET supports only single inheritance of classes, but multiple interfaces can be implemented.

Example:

Public Interface IRunnable Sub Run() End Interface Public Interface ISwimmable Sub Swim() End Interface Public Class Person Implements IRunnable, ISwimmable Public Sub Run() Implements IRunnable.Run ' Implementation End Sub Public Sub Swim() Implements ISwimmable.Swim ' Implementation End Sub End Class

Examples of real mistakes due to lack of knowledge of the nuances of the topic


Story
In a large accounting system, an engineer tried to inherit two classes (e.g., Employee and Manager). The code did not compile, which delayed the project for several days: it was necessary to rework the scheme, separating functionality into interfaces.


Story
A young developer forgot to mark the base class methods as Overridable, but tried to override them in the derived class. Compilation errors occurred, causing the team to spend time on debugging.


Story
In one project, a property in the base class was accidentally left public, and it was incorrectly modified from the descendants, leading to encapsulation violations and subtle bugs.