Abstract Class in VB.NET
MustOverride & MustInherit Keywords in VB.NET
Abstract Method in VB.NET is defined with the MustOverride keyword and Abstract class is defined with the MustInherit Keyword.
Now in VB.NET, the two-dimensional figure class is implemented as follows:
Public MustInherit Class TwoDFigure
Protected d1 As Integer
Protected d2 As Integer
Sub New(d1 As Integer, d2 As Integer)
Me.d1 = d1
Me.d2 = d2
End Sub
MustOverride Sub computeArea()
End Class
The abstract class can only be used by inheriting it. However, its object cannot be created i.e. cannot be instantiated. Recall, Inheritance represents a IS_A relationship. Therefore, a Triangle is a two-dimensional figure, a Rectangle is also a two-dimensional figure. The MustOverride (abstract Method) is overridden( defined or implementation is provided) in the sub class with the Overrides keyword . The following code demonstrate how to use the abstract class.
Public Class Rectangle
Inherits TwoDFigure
Public Sub New(length As Integer, breadth As Integer)
'MyBase keyword in VB.NET is used to pass parameter required by super
'class constructor
MyBase.New(length, breadth)
End Sub
Public Overrides Sub computeArea()
Dim area As Integer
area = d1 * d2
Console.WriteLine("Area of Rectangle " & area)
End Sub
End Class
Public Class Triangle
Inherits TwoDFigure
Public Sub New(tbase As Integer, theight As Integer)
MyBase.New(tbase, theight)
End Sub
'abstract Method is defined with the Overrides Keywords
Public Overrides Sub computeArea()
Dim area As Double
area = (1.0 / 2.0) * d1 * d2
'& is a concatenation operator
Console.WriteLine("Area of Rectangle " & area)
End Sub
End Class
Recall, in VB.NET the reference of the super class can refer to the objects of the sub classes and then it calls the method of that class. It is used to achieve runtime polymorphism. In VB.NET, It is called Dynamic Method Dispatch.
The Rectangle and the Triangle class can be tested by defining a class with the main method as follows:
Module Module1
Sub Main()
'Creating an instance Or an object
'A reference variable of Super class can refer to
'Objects of Super as well as Sub Class
Dim figure As TwoDFigure
figure = New Rectangle(10, 20)
figure.computeArea()
figure = New Triangle(10, 20)
figure.computeArea()
Console.ReadKey()
End Sub
End Module
The abstract method is a unimplemented method in an abstract class. It is provided implementation in the respective sub classes. It archives runtime Polymorphism. However, in VB.NET, the abstract method is defined in the sub class with the Overrides keyword.
Imagine the cut-copy and the paste operation in software. Their implementation varies from one software to another software.
Abstract Class in VB.NET
Reviewed by Syed Hafiz Choudhary
on
September 13, 2023
Rating:
No comments: