Method Overloading in Java
Overloading means declaring multiple methods with the same name but different parameter lists. The compiler picks the best match at compile time based on the argument types.
Example
public class Logger {
public void log(String msg) { ... }
public void log(String msg, Throwable t) { ... }
public void log(int code, String msg) { ... }
public void log(Level level, String msg) { ... }
}
What counts as a different signature
Number of parameters, types, or order. Parameter names don't matter. Return type doesn't matter.
int add(int a, int b) { ... }
long add(long a, long b) { ... } // β
different types
long add(int a, int b) { ... } // β same signature as first β return type alone is not enough
Resolution rules (simplified)
- Most specific match wins.
log(5)pickslog(int)overlog(Integer). - Widening beats boxing.
log(5)with(int)and(long)overloads picks(int); if only(long)and(Integer)exist, picks(long). - Varargs is last resort.
The autoboxing trap
public void remove(int index) { list.remove(index); }
public void remove(Integer value) { list.remove(value); }
remove(1); // picks (int) β removes index 1
remove((Integer) 1); // picks (Integer) β removes value 1
Naming the methods differently (removeAt vs removeValue) is clearer than relying on the subtle overload resolution.
Overloading vs overriding
| Overloading | Overriding | |
|---|---|---|
| Same class or subclass? | Same class (usually) | Subclass |
| Same signature? | No β must differ in parameters | Yes β exactly the same |
| Resolved when? | Compile time | Runtime (dynamic dispatch) |
| Annotation | None | @Override |
Common mistakes
- Overloading where a separate name would be clearer β
send(User)vssend(String email)confuses readers. UsesendUserandsendEmail. - Autoboxing surprises β see above.
- Overloading a method in a parent class vs overriding β without
@Overrideit's a silent bug. Always annotate overrides.
Related
Pillar: Java methods. See also polymorphism, varargs.