Java - Method Overloading
Method Overloading means, when two or more methods have the same name but different parameters.
Below are two types of difference in parameters that java considers for method overloading :
1. The number of parameters are different in two or more methods.
Example :
a. Say there is an 'add' method with three parameters :
int add(int firstNumber, int secondNumber, int thirdNumber)
b. Also there is an 'add' method with two parameters :
int add(int firstNumber, int secondNumber)
c. Also, there is an 'add' method with just one parameter :
int add(int firstNumber)
All the above three methods are said to be overloaded methods and java would treat them as separate methods.
2. The number of parameters are same in two or more methods but have different datatypes.
Example :
a. Say there is an 'add' method with two parameters :
int add(float firstNumber, float secondNumber)
b. Also there is an 'add' method with two parameters :
int add(int firstNumber, int secondNumber)
Since, the datatype of the parameters in two methods do not match(i.e. float and int). The methods are said to be overloaded and java would treat them as separate methods.
So, let us try adding 2 numbers with 'add' method. Then try adding 3 numbers with the overloaded 'add' method.
public class Test{
public static void main(String[] arg){
int firstNum = 5;
int secondNum = 8;
int thirdNum = 2;
int addedResult1;
int addedResult2;
addedResult1 = add(firstNum,secondNum);
System.out.println("The added value of two numbers is : "+addedResult1);
addedResult2 = add(firstNum,secondNum,thirdNum);
System.out.println("The added value of three numbers is : "+addedResult2);
}
//Add method starts here.
static int add(int firstNumber, int secondNumber) {
int result;
result = firstNumber + secondNumber;
return result;
}
//Overloaded Add method starts here.
static int add(int firstNumber, int secondNumber, int thirdNumber) {
int result;
result = firstNumber + secondNumber + thirdNumber;
return result;
}
}
Output :
The added value of two numbers is : 13
The added value of three numbers is : 15
In the main method, at first, we have called the 'add' method with two parameters :
addedResult1 = add(firstNum,secondNum);
Then we have called the 'add' method with three parameters :
addedResult2 = add(firstNum,secondNum,thirdNum);
And java treated both the methods as different methods, since they were overloaded.
Note : We have added 'static' keyword in front of the method, so that it could be accessed from main method.