Click here to Skip to main content
15,885,767 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.74/5 (13 votes)
6 Sep 2013CPOL6 min read 96.6K   1.8K   39   22
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()" <code><code>



VB.NET
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 :  

VB.NET
 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 :  

VB.NET
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 :

Image 1

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

VB.NET
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

VB.NET
 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

VB.NET
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 :

VB.NET
 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 :

Image 2


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 :  

VB.NET
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 <span style="font-size: 12px; white-space: pre-wrap;">Protected</span> 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."  

VB.NET
MyBase.New()
 Initialize(EmpId) 

The blow code shows you the last changes on EmployeeBase Class

 

VB.NET
  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 .   

VB.NET
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 :  

 

VB.NET
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 :

VB.NET
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 :

Image 3

and class diagram will show what exactly happend

Image 4

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United Kingdom United Kingdom
I have studied in software engineering . I am a software engineer who interested in web development and my most interested part is UX/UI design .I realize the web software systems; whereas, I do designing, coding, database designing for web based systems.

Comments and Discussions

 
QuestionDeclare objects dynamically Pin
Oscar Zatarain13-Jan-15 14:25
Oscar Zatarain13-Jan-15 14:25 
QuestionAdding events to the interface Pin
chy00ng7-Jul-14 21:58
chy00ng7-Jul-14 21:58 
AnswerRe: Adding events to the interface Pin
Babak Jahangiri8-Jul-14 1:03
Babak Jahangiri8-Jul-14 1:03 
GeneralRe: Adding events to the interface Pin
chy00ng3-Jan-15 14:36
chy00ng3-Jan-15 14:36 
QuestionUsing Property instead of Function Pin
Sivag7521-Mar-14 19:26
Sivag7521-Mar-14 19:26 
AnswerRe: Using Property instead of Function Pin
Babak Jahangiri3-Apr-14 12:50
Babak Jahangiri3-Apr-14 12:50 
QuestionWhy creating class "Accounting" ? Pin
Member 1037780222-Nov-13 15:11
Member 1037780222-Nov-13 15:11 
AnswerRe: Why creating class "Accounting" ? Pin
Member 1037780223-Nov-13 2:53
Member 1037780223-Nov-13 2:53 
GeneralRe: Why creating class "Accounting" ? Pin
Babak Jahangiri24-Feb-14 8:38
Babak Jahangiri24-Feb-14 8:38 
QuestionSingle Employee Type Pin
Juzer25-Aug-13 3:22
Juzer25-Aug-13 3:22 
AnswerRe: Single Employee Type Pin
Babak Jahangiri25-Aug-13 4:38
Babak Jahangiri25-Aug-13 4:38 
GeneralRe: Single Employee Type Pin
Juzer25-Aug-13 10:32
Juzer25-Aug-13 10:32 
GeneralRe: Single Employee Type Pin
Babak Jahangiri25-Aug-13 17:31
Babak Jahangiri25-Aug-13 17:31 
GeneralRe: Single Employee Type Pin
Juzer27-Aug-13 3:05
Juzer27-Aug-13 3:05 
GeneralRe: Single Employee Type Pin
Babak Jahangiri5-Sep-13 23:02
Babak Jahangiri5-Sep-13 23:02 
GeneralRe: Single Employee Type Pin
Juzer6-Sep-13 4:12
Juzer6-Sep-13 4:12 
AnswerRe: Single Employee Type Pin
Babak Jahangiri6-Sep-13 23:19
Babak Jahangiri6-Sep-13 23:19 
QuestionQuestion on Third iteration Pin
Klaus Luedenscheidt24-Aug-13 18:12
Klaus Luedenscheidt24-Aug-13 18:12 
AnswerRe: Question on Third iteration Pin
Babak Jahangiri24-Aug-13 19:57
Babak Jahangiri24-Aug-13 19:57 
GeneralRe: Question on Third iteration Pin
Klaus Luedenscheidt25-Aug-13 19:56
Klaus Luedenscheidt25-Aug-13 19:56 
AnswerRe: Question on Third iteration Pin
Babak Jahangiri25-Aug-13 20:21
Babak Jahangiri25-Aug-13 20:21 
GeneralRe: Question on Third iteration Pin
Klaus Luedenscheidt25-Aug-13 22:53
Klaus Luedenscheidt25-Aug-13 22:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.