Method Overloading is one of the features in a class having more than one method with the same name. It is the same as Constructor Overloading in java. The methods are differed by their input parameter that is the data type, the number of parameters, and the order of the parameter list.
Note that: Method overloading is not possible by changing the return type of methods.
Now let us see the different ways of overloading methods.
There are two different ways in which the method can be overloaded:
- Method overloading, by changing the data type of Arguments.
- Method overloading, by changing the number of the argument.
1. Method overloading by changing the data type of Arguments.
In this method, the user needs to change the data-type of passing argument for two different methods of the same name and the parameter list must match with that data type accordingly.
The following program shows the example of using Method overloading by changing the data type of Arguments in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class MethOverloadingTest { void add (int x, int y) { System.out.println("sum is "+(x+y)) ; } void add (double x, double y) { System.out.println("sum is "+(x+y)); } } public class Main { public static void main (String[] args) { MethOverloadingTest sum = new MethOverloadingTest(); sum.add (5,5); // method with int parameter is called. sum.add (5.5, 5.5); //method with float parameter is called. } } |
The output of Method overloading:
sum is 10
sum is 11.0
2. Method overloading by changing the number of the argument.
Another way is by changing the number of arguments that is the number of parameters passed when called. We can also keep the argument empty and it will recognize the method with an empty parameter list.
Following is the example method overloading by changing the number of arguments in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class MethOverloadingTest2 { void Info() { System.out.println("Argument List is empty") ; } void Info (String c, int id) { System.out.println("\nName:"+c+" Id:"+id); } void Info (String c, int id, int age) { System.out.println("\nName:"+c+" Id:"+id+" Age:"+age); } } public class Main { public static void main (String[] args) { MethOverloadingTest2 sum = new MethOverloadingTest2(); sum.Info(); //method with empty parameter is called. sum.Info ("Karan",1101); // method with two parameter is called. sum.Info ("Prashant",1102,23); //method with three parameter is called. } } |
The output of Method overloading:
Argument List is empty
Name:Karan Id:1101
Name:Prashant Id:1102 Age:23