Java ยท Chapter 19 of 42

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.

Syntax
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.

Example 1 (java)
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));
  }
}
Output
5
6.0

Java 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.
๐Ÿ’ก Note: Overloading is different from overriding, which happens with inheritance at runtime.

๐Ÿ“ Quick Quiz

1. What must differ between overloaded methods?

2. When is the correct overload chosen?

3. Can two methods differ only by return type to be overloads?