Java Method Overloading
Method overloading lets you define multiple methods with the same name but different parameter lists (different number or types of parameters) within the same class.
The compiler decides which overload to call based on the arguments provided, a form of compile-time polymorphism.
returnType method(TypeA a) { }
returnType method(TypeA a, TypeB b) { }Why overload methods?
Overloading lets you provide multiple ways to call a logically similar operation, like add(int, int) and add(double, double), without needing different names.
Overload resolution rules
Overloads must differ in parameter type or count; return type alone is not enough to distinguish two overloads.
public class Main {
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2.5, 3.5));
}
}5
6.0Java picks the int overload for integer arguments and the double overload for decimal arguments.
Key points
- Overloaded methods share a name but differ in parameters.
- Overload resolution happens at compile time.
- Return type alone cannot distinguish overloads.
- Overloading improves API readability and flexibility.
