Method Overloading and Overriding

Introduction

  • Overloading and Overriding are parts of Polymorphism.
  • Overloading is compile time polymorphism, also known as Early Binding or Static Binding.
  • Overriding is run-time polymorphism, also known as Late Binding or Dynamic Binding.

So first we'll go through the Overloading

Suppose you need to define a method, but you don't have any idea of how many parameters would be there and also don't know the what type of data it would be.

Let's take a method named Insert_Employee.


     class Insert_Employee_Data 
       { 
         public static void Insert_Employee(int EmployeeID) 
         { 
           // Inserts EmployeeID as given and Employee's FirstName and LastName as empty 
         } 
         public static void Insert_Employee(int EmployeeID, string FirstName) 
         { 
           // Inserts EmployeeID and Employee Name as given whereas, LastName as empty 
         } 
         public static void Insert_Employee(int EmployeeID, string FirstName, string LastName) 
         { 
           // Inserts EmployeeID, Employee's FisrtName and LastName as given 
         } 
When your class's behaviors have totally different implementation but are intended for a single target then use Overloading.

Now let's go through Overriding

Take a situation where you need to use the base class's method in a derived class with some add-on.

Suppose you have a price calculation class, which calculates the price and returns it to you.

The price calculation method should be declared as virtual, so that enhancements can be done to it later on (adding some expenses maybe).
  1. class Price_Calculation  
  2. {  
  3.     public decimal UnitPrice { getset; }  
  4.     private int Quantity { getset; }  
  5.   
  6.     public virtual decimal CalculatePrice()  
  7.     {  
  8.         return (UnitPrice * Quantity);  
  9.     }  
  10. }  
  11. /// <summary>   
  12. /// This class also calculates the Price Amount but returns the total amount with Expenses also   
  13. /// </summary>   
  14. class Price_And_Expense_Calculation : PriceCalculation  
  15. {  
  16.     public decimal ExpenseAmount { getset; }  
  17.   
  18.     /// This method does not calculate the price itself, but overrideds the price calculation method and just   
  19.     /// adds the expense amount to it   
  20.   
  21.     public override decimal CalculatePrice()  
  22.     {  
  23.         return (base.CalculatePrice() + ExpenseAmount);  
  24.     }  
  25. }  
I hope you now understand overriding. It means, if your class's behaviors have anything in common and can be shared with other derived forms of classes then they should be overridden.

 

Ebook Download
View all
Learn
View all