Inheritance in Visual Basic .NET

In this article, I will explain you Inheritance in Visual Basic .NET.
  • 2497

In this article, I will explain you Inheritance in Visual Basic .NET

Inheritance

Reusability is an important feature of Object-Oriented Programming. If we can reuse something that already exists it's always time saving and useful rather than creating the same thing again. By reusing the class that already tested and debugged can save the time and effort of testing and developing it again. Inheritance is the process of deriving a new class from an existing class. The existing class is called Base class and the new class is called Derived class. When a Derived class is created through implementation inheritance, It automatically gains all the members and implementation of the Base class. The behavior of the Base class can be changed by writing code in the Derived class. This technique is called overriding. With the new implementations of Derived class inherited methods can also be override. Inheritance allows you to build a hierarchy of related classes and to reuse functionality defined in existing classes. All classes created with Visual Basic are inheritable by default. In Visual Basic we use the Inherits keyword to inherit one class from other. This code show you how to declare the inherit class:

Public Class Base
    ----
        ----
End Class
 
Public Class Derived
    Inherits Base
    'Derived class inherits the Base class
    ----
        ----
End Class


Derived classes inherit, and can extend the methods, properties, events of the Base class. With the use of inheritance we can use the variables, methods, properties, events etc, from the Base class and add more functionality to it in the Derived class. The following code show you how inheritance works:

Imports
System.Console
Module Module1
 
    Sub Main()
        Dim Obj As New Derived()
        WriteLine(Obj.sum())
        Read()
    End Sub
 
End Module
 
Public Class Base
    'base class
    Public A As Integer = 20
    Public B As Integer = 40
 
    Public Function add() As Integer
        Return A + B
    End Function
 
End Class
 
Public Class Derived
    Inherits Base
    'derived class.Class Derived inherited from class Base
    Public C As Integer = 50
 
    Public Function sum() As Integer
        'using the variables, function from base class and adding more functionality
        Return A + B + C
    End Function
 
End Class

The output of this code is:

Output4.gif

Summary

Hope this article help you to understand Inheritance in Visual Basic .NET

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.