Creating Abstract Classes
In Visual Basic .NET we create an abstract class by using the MustInherit keyword. An abstract class like all other classes can implement any number of members. Members of an abstract class can either be Overridable (all the inheriting classes can create their own implementation of the members) or they can have a fixed implementation that will be common to all inheriting members. Abstract classes can also specify abstract members. Like abstract classes, abstract members also provide no details regarding their implementation. Only the member type, access level, required parameters and return type are specified. To declare an abstract member we use the MustOverride keyword. Abstract members should be declared in abstract classes.
Implementing Abstract Class
When a class inherits from an abstract class, it must implement every abstract member defined by the abstract class. Implementation is possible by overriding the member specified in the abstract class. The following code demonstrates the declaration and implementation of an abstract class.
| Module Module1 Public MustInherit Class AbstractClass 'declaring an abstract class with MustInherit keyword Public MustOverride Function Add() As Integer Public MustOverride Function Mul() As Integer 'declaring two abstract members with MustOverride keyword End Class Public Class AbstractOne Inherits AbstractClass 'implementing the abstract class by inheriting Dim i As Integer = 20 Dim j As Integer = 30 'declaring two integers Public Overrides Function Add() As Integer Return i + j End Function 'implementing the add method Public Overrides Function Mul() As Integer Return i * j End Function 'implementing the mul method End Class Sub Main() Dim abs As New AbstractOne() 'creating an instance of AbstractOne WriteLine("Sum is" & " " & abs.Add()) WriteLine("Multiplication is" & " " & abs.Mul()) 'displaying output Read() End Sub End Module |
The output of above code is the image below.
No comments:
Post a Comment