Method Overloading
TL;DR
- Method Overloading occurs when a class has multiple methods with the exact same name, but different parameters.
- It is a form of Compile-Time Polymorphism (Static Binding).
- Methods must differ in the number of parameters, or the data types of the parameters.
Concept
Overloading makes code much more readable. Instead of creating methods like printInteger(), printString(), and printDouble(), you can just name them all print() and let the Java compiler figure out which one to call based on what arguments you pass.
Important Rules
- Return type does not matter: You cannot overload a method simply by changing its return type. The parameter list must be different.
- Access modifiers do not matter: Changing from
publictoprivatedoes not make a method overloaded.
Examples
class MathUtils {
// 1. Adds two integers
public int add(int a, int b) {
return a + b;
}
// 2. Overloaded: Different number of parameters
public int add(int a, int b, int c) {
return a + b + c;
}
// 3. Overloaded: Different data types
public double add(double a, double b) {
return a + b;
}
/*
ILLEGAL OVERLOAD (Compile Error):
public double add(int a, int b) {
return (double) (a + b);
}
Reason: The parameter list (int, int) is identical to method #1.
Return type alone is not enough.
*/
}
public class OverloadingExample {
public static void main(String[] args) {
MathUtils math = new MathUtils();
System.out.println(math.add(5, 5)); // Calls #1
System.out.println(math.add(5, 5, 5)); // Calls #2
System.out.println(math.add(5.5, 4.5)); // Calls #3
}
}
Interview Questions
Q: Can we overload the main method in Java?
A: Yes, absolutely. You can write as many public static void main() methods as you want, provided they take different parameters (e.g., main(int args)). However, when you execute the class, the JVM will strictly look for the standard main(String[] args) signature to launch the application.
Q: Why is changing the return type not enough to overload a method?
A: Because when calling a method, the developer is not required to assign the return value to a variable. For example, if you just call math.add(5, 5); and discard the result, the compiler has absolutely no idea whether you intended to call the int version or the double version. This ambiguity is why Java forbids it.