Wednesday, May 15, 2013

Inheritance in Visual Basic.NET

Inheritance in VB.net

     Inheritance in VB.net is method by which the properties of the base classes are added to the derived classes. In Vb.net the keyword Inherits is used in the derived class to specify its base class.

The MustInherit keyword is used to speciy that class can be used only as a base class,NotInheritable is used to specify that a class cannot be inherited.
Example:
   Module Module1
    Public Class s1
        Public a As Integer = 5
        Public Function val() As Integer
            Return a
        End Function
    End Class

    Public Class s2
        Inherits s1
        Public c As Integer = 20
        Public Function add() As Integer
            Return c + a
        End Function
    End Class

    Sub Main()
        Dim res As New s2
        System.Console.WriteLine("Final Value is::")
        System.Console.WriteLine(res.add())
        Console.Read()
    End Sub

End Module
Result:
    Final Value is: 25
Description:
In the above example the value of a is inherited to from base class s1 to the derived class s2. Using the instance res of class s2 the values of 'a' as well as 'c' is added to give the result.

No comments:

Post a Comment