Method overloading is the ability to create multiple methods with the same name but different parameters (type, order, number) within a single class. This approach allows for logically grouping similar operations and improves code readability.
public class MathUtil { public int sum(int a, int b) { return a + b; } public double sum(double a, double b) { return a + b; } public int sum(int a, int b, int c) { return a + b + c; } }
Question: Can methods be overloaded based only on the return type (without changing parameters)?
Answer: No. Overloading is only possible when there is a difference in the parameter list. A difference based only on return type will result in a compilation error.
void foo(int a) {} int foo(int a) { return 1; } // Error! Return type is not considered in overloading.
Story
In one project, a developer created two methods:
public void process(int x, double y) {...} public void process(double x, int y) {...}When calling
process(5, 10), the compiler could not choose the right version, leading to an ambiguity error. This delayed the module delivery.
Story
In an application, the methods were overloaded based on varargs and arrays:
public void log(String... messages) {...} public void log(String[] messages) {...}Passing an array
String[] datadid not always invoke the expected overload, resulting in incorrect logging of some data — part of the information was lost! The distinction between an array and varargs turned out to be critical.
Story
A developer overloaded class methods without considering type autoboxing:
public void save(Integer i) {...} public void save(int i) {...}When calling
save(null), a NullPointerException occurred at the call site with primitive int, as Java selects the most specific type (int), but null cannot be converted to a primitive!