Method Overloading


Method Overloading is when a class has 2 or more methods by the same name but with different parameters.

Suppose we have to perform addition of some given numbers but there can be any number of arguments, then it will be easier for us to create methods such as add(int, int), add(int, int, int) instead of creating a(int, int), b(int, int, int).

There are 2 ways to overload a method:

  1. By changing number of arguments
  2. By changing the data type

1. By changing number of arguments

In this example, we have created two methods with same name but with different parameters, the first add() method performs addition of 2 numbers while second add() method performs addition of 3 numbers.


Example:

class AddNumbers
{  
    static int add(int a,int b)
    {
        return a+b;
    }

    static int add(int a,int b,int c)
    {
        return a+b+c;
    }
}  

class MethodOverloadingExample
{  
    public static void main(String[] args)
    {  
        System.out.println(AddNumbers.add(7,4));
        System.out.println(AddNumbers.add(3,5,8));
    }
}

Output:

11
16

2. By changing data type of arguments>

In this example, we have created two methods with same name but different in data type. The first add() method receives two integer arguments while the second add() method receives two double arguments.


Example:

class AddNumbers
{
    static int add(int a, int b)
    {
        return a+b;
    }
    static double add(double a, double b)
    {
        return a+b;
    }
}

class MethodOverloadingExample
{  
    public static void main(String[] args)
    {  
        System.out.println(AddNumbers.add(4,7));
        System.out.println(AddNumbers.add(5.46,7.32));
    }
}

Output:

11
12.78