|
OOP with VB
Inheritance
A key feature of OOP is reusability. It's always time saving and useful if we can
reuse something that already exists rather than trying to create the same thing again
and again. Reusing the class that is tested, debugged and used many times can save
us time and effort of developing and testing it again. Once a class has been written
and tested, it can be used by other programs to suit the program's requirement. This
is done by creating a new class from an existing class. The process of deriving a
new class from an existing class is called Inheritance. The old class is called the base
class and the new class is called derived class.
The derived class inherits some or everything of the base class. In Visual Basic we
use the Inherits keyword to inherit one class from other.
The general form of deriving a new class from an existing class looks as follows:
Public Class One
---
---
End Class
Public Class Two
     Inherits One
---
---
End Class
|
Using Inheritance we can use the variables, methods, properties, etc, from the base
class and add more functionality to it in the derived class. The following code demonstrates
the process of Inheritance in Visual Basic.
Imports System.Console
Module Module1
Sub Main()
Dim ss As New Two()
WriteLine(ss.sum())
Read()
End Sub
End Module
Public Class One
'base class
Public i As Integer = 10
Public j As Integer = 20
Public Function add() As Integer
Return i + j
End Function
End Class
Public Class Two
    Inherits One
'derived class. class two inherited from class one
Public k As Integer = 100
Public Function sum() As Integer
'using the variables, function from base class and adding more functionality
Return i + j + k
End Function
End Class
|
Output of above code is sum of i, j, k as shown in the image below.
|