Inheritance in Object-oriented Programming in VB.NET

 INHERITANCE:

 

It is a primary feature of Object-Oriented Programming,

just like encapsulation and polymorphism, inheritance is an element of Object-Oriented Programming by which we can derive the members of one class the "base class" for another class the "child class". When we derive a class from a base class, the derived class will inherit all members of the base class except constructors. With the help of inheritance we can create an object that can reuse code. Once a method is defined in a super class, it is automatically inherited by all subclasses, they share a common set of properties. Object-Oriented Programming allows classes to inherit commonly used state and behavior from other classes. By using inheritance we can reduce the testing and developing efforts. 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 the derived class the inherited methods can also be overrided. 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 another.


This code shows 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 and 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.


 

Imports System. Console
Module Module1
 
    Sub Main()
        Dim Obj As New Subclass()
        WriteLine(Obj.sum())
        Read()
    End Sub
 
End Module
 
Public Class Superclass
    'base class
    Public X As Integer = 5
    Public Y As Integer = 15
 
    Public Function add() As Integer
        Return X + Y
    End Function
 
End Class
 
Public Class Subclass
    Inherits Base
    'derived class.Class Subclass inherited from class Superclass
    Public Z As Integer = 25
 
    Public Function sum() As Integer
        'using the variables, function from superclass and adding more functionality
        Return X + Y + Z
    End Function
 
End Class


Summary


I hope this article helps you to understand Inheritance in Object-Oriented Programming.

Up Next
    Ebook Download
    View all
    Learn
    View all