What is Method Overloading?
It is a feature that allows a class to have more than one method of same name, but different parameters. Method can be overload if:-
- No of parameters are different in two methods
- Type of parameters are different
- Sequence of parameters are different
Note:- If two methods have same name, same no of parameters, same sequence of parameters and same type of parameters but different return type, then the methods are not overloaded. It will show compile time error.
Why do we need Method Overloading?
If we need to perform same kind of operation with different data inputs, we go for method overloading. Below is an example of addition operation with different inputs to explain method overloading. It is an example of static polymorphism or early binding or compile time binding. Here, binding of method call to its definition happens at compile time.
public class MethodOverloading_Demo {
public void Calculation(int a, float b) {
System.out.println("Sum of 2 numbers :"+(a+b));
}
//Different type of parameters
public void Calculation(float x, float y) {
System.out.println("Sum of 2 numbers :"+(x+y));
}
//Different number of parameters
public void Calculation(int i, int j, int k) {
System.out.println("Sum of 3 numbers :"+(i+j+k));
}
//Different sequence of parameters
public void Calculation(float p, int r) {
System.out.println("Sum of 3 numbers :"+(p+r));
}
public static void main(String[] args) {
MethodOverloading_Demo add = new MethodOverloading_Demo();
//Call overloaded methods
add.Calculation(5,12f);
add.Calculation(13f,12.0f);
add.Calculation(22,33,50);
add.Calculation(11f, 10);
}
}
Output
Sum of 2 numbers :17.0
Sum of 2 numbers :25.0
Sum of 3 numbers :105
Sum of 3 numbers :21.0
What is Type Promotion?
When a data type of smaller type, promote to bigger type, it called type promotion. Suppose a method has double data type and object provides float, then the program works fine. Float will be promote to double.
Let us explain this with an example. In the below example, object has provided float data type, but method has double data type, so there is type promotion.
public class Addition {
public void Calculation(int a, int b) {
System.out.println("Sum of 2 numbers :"+(a+b));
}
public void Calculation(int x, double y) {
System.out.println("Sum of 2 numbers :"+(x+y));
}
public static void main(String[] args) {
Addition add = new Addition();
//Type Promotion method
add.Calculation(5,12);
add.Calculation(13,12f);
}
}
Output
Sum of 2 numbers :17
Sum of 2 numbers :25.0