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:
Protected modifier or use Overridable/Overrides for methods that should be overridden.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:
Implements keyword.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
Story
In a large accounting system, an engineer tried to inherit two classes (e.g.,EmployeeandManager). 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 asOverridable, 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.