|
OOP with VB
Abstract Classes
An abstract class is the one that is not used to create objects. An abstract class
is designed to act as a base class (to be inherited by other classes). Abstract class
is a design concept in program development and provides a base upon which other classes
are built. Abstract classes are similar to interfaces. After declaring an abstract
class, it cannot be instantiated on it's own, it
must be inherited. Like interfaces, abstract classes can specify members that
must be implemented in inheriting classes. Unlike interfaces, a class can inherit
only one abstract class. Abstract classes can only specify members that should be
implemented by all inheriting classes.
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.
|