Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Advantage of using Interface and Inheritance in VB.NET (OOP)

0.00/5 (No votes)
6 Sep 2013 2  
This article will explain you tangible and functional example of using Interface with inheritance in VB.NET for Object Oriented Programming


 Download OOP_Inteface_Inheritance-noexe.zip - Source Code In C# and VB.NET Without EXE File ,
 Visual Studio 10 Project File
 
Article Version : 2.03

Introduction      

Most of beginner programmer may not know and use the Object Oriented facilities in their codes , although they can write bunch of lines ; the codes are not readable for the next developers and fall them in trouble.

one of the facility in OOP is interface , "An interface contains only the signatures of methods, properties, events or indexers.
A class or struct that implements the interface must implement the
members of the interface that are specified in the interface definitionvoid." as Microsoft said.

In this article I explain the simple example of using interface and combine with inheritance concept in OOP.
the example will be useful for those novice VB.NET programmer who had problem with understanding to use Interface and Inheritance beside each other .  

The article Codes written in Visual Basic.Net language and might be useful in Windows Application , Web Application (ASP.NET) , Mobile Application and etc .

Background  

before you continue reading this article please be aware I assume you know about the theoretical concept of OOP programming , Such as Class ,Methods , Property , Inheritance .

For more information about the concepts of Object Oriented Programming such as class , Methods , Property , Inheritance , Access modifier please search on codeproject.com or Microsoft MSDN.

Scenario  

Imagine you got order from your software project manager and you should prepare three different classes for three types of users in the system , some users have common properties such as NAME , LAST NAME , AGE , TELEPHONE , ADDRESS and etc .  

you provide a parent class and put all of the common Properties inside that then create three child classes .

if we assume we have "SALES" users , "Managers" users , "Developers" users ; finally we should have three class with their names , and one parent class name "EmployeeBase" , that are very obvious so far .

One of the method which your Software Project Manager wants is "GetSalary()" , and which mean the classes should get the salary from database according to Users Types , and any time you need to use "GetSalary()" method you should understand first the "current user type" then create appropriate instance of the user class then call "GetSalery()"



If UserType = "Developer" Then 
 
Dim objectDeveloper As New EmployeeDeveloper
objectDeveloper.GetSalery()
 
End If 
If UserType = "Manager" Then 
 
Dim objectManager As New EmployeeManager
objectManager.GetSalery()
 
End If   

the above codes are completely ugly and not acceptable by All professional software developers seniors .

Using the code  

For solving the problem I try to lead you deep into the OOP concept and after four iteration we will have clean , nice , OOP based Code and finally we have a piece of codes which are acceptable for most Software Seniors and Software Team Leaders .  

Here Interface concept help us to make a change in the codes and make them better and I will explain the evolution steps of codes .

Iteration 1 :  

 Public Interface IEmployee
        Function GetSalary() As Double
        Function GetEmpType() As String
 End Interface  
   
 
Public Class EmployeeManager
        Inherits EmployeeBase
        Implements IEmployee
 
        Sub New()
 
        End Sub
         
        Public Function GetSalary() As Double Implements IEmployee.GetSalary
            Return 2300.0
        End Function
 
        Public Function GetEmpType() As String Implements IEmployee.GetEmpType
 
            Return "I am an Employee >> 'Manager' "
 
        End Function
 
 End Class

then we have tow other classes which same implementation (Refer to source Code File)
When We need to use it :  

 
Module Main_Module
 
    Sub Main()
 
        Dim oEmp As IEmployee
 
        oEmp = New EmployeeDeveloper
        Console.WriteLine(oEmp.GetEmpType())
        Console.WriteLine("The Salary is : " & oEmp.GetSalary())
 
        oEmp = New EmployeeManager
        Console.WriteLine(oEmp.GetEmpType())
        Console.WriteLine("The Salary is : " & oEmp.GetSalary())
 
 End Sub
 
End Module
 
 

Then Result gonna be like this :

after the first iteration our problem has solved so far and you have learned how to use interface and why we need interface ,you might ask Is that all ?

The second problem shows itself when your Software Project Manager wants you to Calculate the each Employee's salary according the work time and their wage percent , then you should forget GetSalery() method and improve your codes to get better result and It is better we create another class who has duty in calculate the salary and I called it "Accounting" Class .   

Iteration 2 :

I added another function signature in the interface

    Public Interface IEmployee
 
        Function GetSalary() As Double
        Function GetEmpType() As String
        Function GetWorkTime() As Integer
        Function GetExtraWagePercent() As Short
 
    End Interface
 

I have Added GetExtraWagePercent() method in All three child class

  Public Class EmployeeManager
        Inherits EmployeeBase
        Implements IEmployee
 
       ' Public Function GetSalary() As Double Implements IEmployee.GetSalary
       '     Return 2300.0
       ' End Function

        Public Function GetWorkTime() As Integer Implements IEmployee.GetWorkTime
            Return 210
        End Function
 
        Public Function GetExtraWagePercent() As Short Implements IEmployee.GetExtraWagePercent
            Return 1.3
        End Function
 
        Public Function GetEmpType() As String Implements IEmployee.GetEmpType
 
            Return "I am an Employee >> 'Manager' "
 
        End Function
 
 End Class
 
 

and another two classes also follow the same implementation but diffrent Wage Percent Amount and etc
(Reffer to Source Code of this project )

I also create an "Acounting" Class

 Public Class Accounting
 
        Public Function CalculateSalery(employee As IEmployee) As Double
 
         'For Ex : 5$ per hours
         Return employee.GetWorkTime * 5 * employee.GetExtraWagePercent
 
        End Function

you should connect these classes to "Accounting" Class and the class
should provide you CalculateSalery() methods which are be able to calculate the salery with out the class does not need to know about another class functions.

Then in main module we can use this as below :

 Module Main_Module
 
    Sub Main() 
 
      Dim oEmp As IEmployee
      Dim oAccounting As New Accounting
      oEmp = New EmployeeManager
        Console.WriteLine(oEmp.GetEmpType())
        Console.WriteLine("My Salary is : " & oAccounting.CalculateSalery(oEmp))
 
      oEmp = New EmployeeSales
        Console.WriteLine(oEmp.GetEmpType())
        Console.WriteLine("My Salary is : " & oAccounting.CalculateSalery(oEmp))
 

      oEmp = New EmployeeDeveloper
        Console.WriteLine(oEmp.GetEmpType())
        Console.WriteLine("My Salary is : " & oAccounting.CalculateSalery(oEmp))
 
  End Sub
 
End Module

and then so on you can improve your codes.

Then Result gonna be like this :


Remember I use inheritance to access the common properties for Example : Name

Iteration 3 :

Now in third Iteration I want to Add method in Accounting class which be able to beside calculate the salary also be able write the employee name but I don't want connected to database in each class , Just one place and that is in Parent Class (EmployeeBase), hence I need to manipulate the EmployeeBase and just add one property "Name" As Example and another problem is parent class dot know about which Name should be return thus I need to pass the Employee Id from each Child Class to Parent Class and As you Know in OOP we can Acess to the Parent Class from the Child Constructor Like below example :  

MyBase.New()

We Need to write Initialize Sub for All three classes which be able to get Employee ID from the User Interface (UI)(According to Klaus Luedenscheidt's Comment I improved this part) and then we just need to call Initialize Sub in Each Child Class Constructor. The Initialize Sub Can Get the data from the DataBase (XML-SQL Server - any ).
 according the  Employee Id which has given to new child Class Instance (During the calling , here this happened at the main module) 

Notice : The Access Modifier of  Initialize Sub Is Protected which means all child class can use this SUB routine , And Its obvious the EMP ID will send to Initialize class from the Child Class Constructor. Hence each child class have 2 Constructor : 

First one : is for making an instance (NORMAL)
Second one : is used when we want to Work with available data 

"Example for Second Manner : Imagine you just want to ADD Employee in the DB , Just need to Use the first Constructor , but when you decide to Delete or Modify the Employee you shall to use the second constructor."  

MyBase.New()
 Initialize(EmpId) 

The blow code shows you the last changes on EmployeeBase Class

 

  Public Class EmployeeBase 
<pre>        Private _name As String 
        Public Property Name As String
            Get
                Return _name
            End Get
            Set(value As String)
                _name = value
            End Set
        End Property
        Sub New()
            Name = "-----"
        End Sub
        Protected Sub Initialize(ByVal EmpId As Integer) 
            'Normally here we will access the database to retrieve the employees data 
            'For Example I Connected To Database Then I Get the Employee Name According
            ' to Their Employee Ids 
            'Open Connection
            'Get Data
            Select Case EmpId
                Case 1
                    Name = "Babak Manager"
                Case 2
                    Name = "Ali Developer"
                Case 3
                    Name = "Mike Sales"
                Case Else 
            End Select 
            'Close Db Connection  
        End Sub 
    End Class   
 

 And we need to write second Constructor for all "Child Classes" and also I write two function singnature GetEmployeeNameAndSalery() , GetEmployeeName() in the interface IEmployee and then I write the related functions in child clasess to show how Accounting Class can get EmployeeName From the Child Class without direct access to them .   

Public Class EmployeeSales
        Inherits EmployeeBase
        Implements IEmployee
 
        'first Constructor of Employee Sales Class 
        Sub New()
 
        End Sub
 
        'second Constructor of Employee Sales Class 
        Sub New(ByVal EmpId As Integer)
            MyBase.New()
            Initialize(EmpId)
        End Sub

        Public Function GetWorkTime() As Integer Implements IEmployee.GetWorkTime
            Return 142        
        End Function  

        Public Function GetExtraWagePercent() As Short Implements IEmployee.GetExtraWagePercent
            Return 1.1
        End Function
 
        Public Function GetEmployeeNameAndSalery() As String Implements IEmployee.GetEmployeeNameAndSalery
 
            Dim objAccounting As New Accounting
            Return MyBase.Name & " - " & objAccounting.CalculateSalery(Me)
 
        End Function
 
        Public Function GetEmployeeName() As String Implements IEmployee.GetEmployeeName
            Return MyBase.Name
        End Function
 
        Public Function GetEmpType() As String Implements IEmployee.GetEmpType
 
            Return "I am an Employee >> 'Sales' "
 
        End Function
 
    End Class 

 
 Finally the IEmployee Interface will look like this :  

 

    Public Interface IEmployee

        Function GetSalary() As Double
        Function GetWorkTime() As Integer
        Function GetExtraWagePercent() As Short
        Function GetEmpType() As String
        Function GetEmployeeNameAndSalery() As String
        Function GetEmployeeName() As String

    End Interface

and accounting class will looks like this :

 Public Class Accounting

        Private _employeeId As Short

        Public Property EmployeeId As Short
            Get
                Return _employeeId
            End Get
            Set(value As Short)
                _employeeId = value
            End Set
        End Property

        Public Function CalculateSalery(employee As IEmployee) As Double
            'For Ex : 5$ per hours
            ' Wana need different price for each type of Employee 
            ' Defind it in Interface and get it from each Child Class :)


            Return employee.GetWorkTime * 5 * employee.GetExtraWagePercent

        End Function

        Public Function CalculateSaleryAndName(employee As IEmployee) As String

            
            Dim EmpSalery As Double = CalculateSalery(employee)
            Return employee.GetEmployeeNameAndSalery

        End Function

        Public Function Customize_CalculateSaleryAndName(employee As IEmployee) As String

       
            Dim EmpSalery As Double = CalculateSalery(employee)
            Dim EmpName As String = employee.GetEmployeeName

            Return "Employee Name is : " & EmpName & " - Employee Salery is : " & EmpSalery & " $"

        End Function


    End Class

then the result will be like this :

and class diagram will show what exactly happend

Conclusion  

Object Oriented Programming will be very interesting topic if you be lazy in extra code writing and also it helps to after-you developers to understand your code and grow the program which you have written but if you are not care to the concept the others developers will not care to you and ruin all your codes which you have created and then start from new project. which using the OOP concept and facilities we can have usable and robust codes . 

Download OOP_Inteface_Inheritance-noexe.zip
 ( Source Code In C# and VB.NET) 

History   

1- ver 2 : Update one has effected , Add Initialize method  to avoid creating instance of the base class - 9/6/2013 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here