This is a detailed analysis of Abstract classes and methods in VB.NET with some concrete examples.
The keyword abstract can be used with both classes and methods in VB.NET to declare them as abstract.
The classes, which we can't initialize, are known as abstract classes. They provide only partial implementations. But another class can inherit from an abstract class and can create their instances.
For example, an abstract class with a non-abstract
method.
Imports System
MustInherit
Class MyAbs
Public Sub
NonAbMethod()
Console.WriteLine("Non-Abstract Method")
End Sub
'NonAbMethod
End
Class 'MyAbs
Class
MyClass
Inherits MyAbs
End Class
'MyClass]
Class MyClient
Public
Shared Sub Main()
'MyAbs mb = new MyAbs();//not possible to create
an instance
Dim mc
As New
MyClass()
mc.NonAbMethod() ' Displays 'Non-Abstract Method'
End
Sub 'Main
End
Class 'MyClient
An abstract class can contain abstract and non-abstract
methods. When a class inherits from an abstract, the derived class must
implement all the abstract methods declared in the base class.
An abstract method is a method without any method body. They are implicitly
virtual in VB.
Imports System
MustInherit
Class MyAbs
Public Sub
NonAbMethod()
Console.WriteLine("Non-Abstract Method")
End Sub
'NonAbMethod
Public
MustOverride
Sub AbMethod()
' An abstract method
End
Class 'MyAbs
Class
MyClass
Inherits MyAbs
'must implement base class abstract methods
Public
Overrides
Sub AbMethod()
Console.WriteLine("Abstarct method")
End Sub
'AbMethod
End
Class 'MyClass
Class MyClient
Public
Shared Sub Main()
Dim mc As
New [MyClass]
mc.NonAbMethod()
mc.AbMethod()
End Sub
'Main
End
Class 'MyClient
But by declaring the derived class also abstract, we can avoid the
implementation of all or certain abstract methods. This is what is known as
partial implementation of an abstract class.
Imports System
MustInherit
Class MyAbs
Public
MustOverride Sub AbMethod1()
Public
MustOverride Sub AbMethod2()
End Class
'MyAbs
'not necessary to implement all abstract methods
'partial implementation is possible
MustInherit
Class MyClass1
Inherits MyAbs
Public
Overrides Sub AbMethod1()
Console.WriteLine("Abstarct method #1")
End Sub
'AbMethod1
End
Class 'MyClass1
Class [MyClass]
Inherits MyClass1
Public
Overrides Sub AbMethod2()
Console.WriteLine("Abstarct method #2")
End Sub
'AbMethod2
End
Class '[MyClass]
Class MyClient
Public
Shared Sub Main()
Dim mc As
New [MyClass]
mc.AbMethod1()
mc.AbMethod2()
End Sub
'Main
End
Class 'MyClient
In VB, an abstract class can inherit from another non-abstract class. In
addition to the methods it inherited from the base class, it is possible to add
new abstract and non-abstract methods as showing below.
Join the conversation! Your thoughts help the community grow.