Search This Blog

Monday, July 15, 2013

Abstract classes, MustInherit, MustOverride , Overrides VB NET

VB.NET > OOP > Abstract Class

Abstract classes specify members that must be implemented in the inheriting classes. Any class can inherit only from one abstract class. You we cannot create objects of an abstract class.

MustInherit
Specifies that a class can be used only as a base class and that you cannot create an object directly from it.

MustOverride  
Specifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can be used.

Overrides
Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.




Example:

Public Class Form1
  Public MustInherit Class Employee

    Private mFirstName As String
    Private mLastName As String

    Public Sub New(ByVal FirstName, ByVal LastName)
      mFirstName = FirstName
      mLastName = LastName
    End Sub

    Public Property FirstName() As String
      Get
        Return mFirstName
      End Get
      Set(ByVal value As String)
        mFirstName = value
      End Set
    End Property

    Public Property LastName() As String
      Get
        Return mLastName
      End Get
      Set(ByVal value As String)
        mLastName = value
      End Set
    End Property

    Public MustOverride Function Income() As Double
  End Class

  Public Class Teacher
    Inherits Employee

    Private mSalary As Double

    Public Sub New(ByVal FirstName, ByVal Lastname, ByVal salary)
      MyBase.New(FirstName, Lastname)
      mSalary = salary
    End Sub

    Public Property Salary() As String
      Get
        Return mSalary
      End Get
      Set(ByVal value As String)
        mSalary = value
      End Set
    End Property

    Public Overrides Function Income() As Double
      Return Salary() * 1.2
    End Function
  End Class

  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim mTeacher As New Teacher("John", "Smith", 100)
    Dim sal = mTeacher.Income ' 120
  End Sub

End Class