Method Overloading in OOPs

Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a function in more than one form.

Method Overloading in OOPs
Method Overloading, OOPs, Programming, thetechfoyer, thetechfoyer.com

This Articles helps you to understand the concept of Method Overloading in OOPs

A user can implement function overloading by defining two or more functions in a same class sharing the same name, but with different method signatures (i.e. the number of the parameters, order of the parameters, and data types of the parameters).



Method overloading can be achieved by the following:

  • By changing the number of parameters in a method
  • By changing the order of parameters in a method
  • By using different data types for parameters


Suppose we want addition, but with different types, we can achieve like following easly.

static int PlusMethodInt(int x, int y)
{
  return x + y;
}

static double PlusMethodDouble(double x, double y)
{
  return x + y;
}

static void Main(string[] args)
{
  int myNum1 = PlusMethodInt(8, 5);
  double myNum2 = PlusMethodDouble(4.3, 6.26);
  Console.WriteLine("Int: " + myNum1);
  Console.WriteLine("Double: " + myNum2);
}



Why we Overload here?
Since both methods are doing same thing, so Instead of defining two methods that should do the same thing, it is better to overload one.

static int PlusMethod(int x, int y)
{
  return x + y;
}

static double PlusMethod(double x, double y)
{
  return x + y;
}

static void Main(string[] args)
{
  int myNum1 = PlusMethod(8, 5);
  double myNum2 = PlusMethod(4.3, 6.26);
  Console.WriteLine("Int: " + myNum1);
  Console.WriteLine("Double: " + myNum2);
}



In Case of Method overloading, compiler identifies which overloaded method to execute based on number of arguments and theiry data types during compilation itself.

Overloading Vs Overriding Vs Inheritance
Overloading has different function signatures while overriding has the same function signatures.
Inheritance refers to using the structure and behaviour of a superclass in a subclass.



Rules of Method Overloading
1. Do not use ref or out modifiers in overloaded members.