Visual Basic .NET/Inheritance

Inheritance

edit

Inheritance is mainly used to reduce duplication of code. By using the Inherits keyword, you can extend and modify an existing class to have additional properties and methods.

For example, imagine we have an existing class called "Person":

  Public Class Person
       Public FirstName As String
       Public LastName As String
       Public DateOfBirth As Date
       Public Gender As String
       Public ReadOnly Property FullName() As String
           Get
               Return FirstName & " " & LastName
           End Get
       End Property
   End Class

Now imagine we wanted to create a special class called "Customer", which had all the properties of "Person", but also additional properties called "CustomerID" and "CustomerType". We could just make a different class with similar properties as follows:

  Public Class Customer
       Public FirstName As String
       Public LastName As String
       Public DateOfBirth As Date
       Public Gender As String
       Public ReadOnly Property FullName() As String
           Get
               Return FirstName & " " & LastName
           End Get
       End Property
       Public CustomerID As String
       Public CustomerType As String
   End Class

An alternative approach, however is to use the Inherits keyword as follows:

   Public Class Customer
       Inherits Person
       Public CustomerID As String
       Public CustomerType As String
   End Class

"Inherits Person" automatically gives the new "Customer" class all the properties and methods of the "Person" class, as well as the two new properties. This approach also has several advantages:

  • We don't have to re-type the FirstName, LastName, DateOfBirth etc properties
  • When properties and methods of the "Person" class are updated, the "Customer" class need not be rewritten as well.
  • The .FullName property needs to be debugged in only one place
  • Any code that uses a "Person" object can also use a "Customer" object.