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)

  1. Most specific match wins. log(5) picks log(int) over log(Integer).
  2. Widening beats boxing. log(5) with (int) and (long) overloads picks (int); if only (long) and (Integer) exist, picks (long).
  3. 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

OverloadingOverriding
Same class or subclass?Same class (usually)Subclass
Same signature?No β€” must differ in parametersYes β€” exactly the same
Resolved when?Compile timeRuntime (dynamic dispatch)
AnnotationNone@Override

Common mistakes

  • Overloading where a separate name would be clearer β€” send(User) vs send(String email) confuses readers. Use sendUser and sendEmail.
  • Autoboxing surprises β€” see above.
  • Overloading a method in a parent class vs overriding β€” without @Override it's a silent bug. Always annotate overrides.

Related

Pillar: Java methods. See also polymorphism, varargs.