What is Method Overloading?
Method overloading allows programmers to use multiple methods with the same name. The methods are differentiated with their number and type of method arguments. Method overloading is an example of the polymorphism feature of an object oriented programming language.
Method overloading can be achieved by the following:
In the below example, there are three methods with the same names but each method differs in number of parameters and also types of parameters. This method is called method overloading.
Method overloading can be achieved by the following:
- By changing number of parameters in a method
- By changing the order of parameters in a method
- By using different data types for parameters
In the below example, there are three methods with the same names but each method differs in number of parameters and also types of parameters. This method is called method overloading.
Example:
class Program
{
static void Main(string[] args)
{
MethodOverloading_Example obj = new MethodOverloading_Example();
Console.WriteLine("Method 1:{0}", obj.add(5, 10));
Console.WriteLine("Method 2:{0}", obj.add(5, 10,15));
Console.WriteLine("Method 3:{0}", obj.add(10.4f, 15.4f,17.6f));
Console.ReadLine();
}
}
class MethodOverloading_Example
{
public int add(int a, int b) //two int type Parameters method
{
return a + b;
}
public int add(int a, int b, int c) // three int type Parameters with same method same as above
{
return a + b + c;
}
public float add(float a, float b, float c) //three float type Parameters with same method same as above two method
{
return a + b + c;
}
}
No comments:
Post a Comment
Please let me know if you have any feedback or doubts.