Java Method Overloading

Java Method Overloading

With method overloading, multiple methods can have the same name with different parameters.

Consider the following example, which has two methods that add numbers of different types:

Without Overloading

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

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

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

Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the plusMethod method to work for both int and double:

With Overloading

public class Main {
  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); } }

Note: Multiple methods can have the same name as long as the number and/or type of their parameters are different. This is known as method overloading.


Why Overload Methods?

Method overloading provides a way to have a single method name that can operate on different types or numbers of arguments. This improves code readability and reusability.

For example, the built-in System.out.println() method is overloaded. You can pass it a String, an int, a double, a boolean, etc., and it knows how to print each one correctly. Without overloading, you would need separate methods like printlnString(), printlnInt(), etc., which would be much more cumbersome.