Lesson 23 +10 XP

Method Overloading

Method Overloading

Method overloading means multiple methods share the same name but have different parameters.

Overloading example

static int plusMethod(int x, int y) {
  return x + y;
}

static double plusMethod(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethod(8, 5);
  double myNum2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

How Java decides

Java picks the right method based on the number and types of arguments you pass:

  • plusMethod(8, 5) uses the int version.
  • plusMethod(4.3, 6.26) uses the double version.

Why overload

  • Use the same name for similar operations.
  • Support different types or different numbers of arguments.
  • Keep your code readable and consistent.

Rules

The methods must differ in the parameter list (type, order, or count). The return type alone is not enough to overload.

TL;DR

  • Overloading = same method name, different parameters.
  • Java picks the version matching the argument types.
  • The return type alone does not distinguish overloaded methods.