๐ŸŽ“ A1Learner
๐Ÿ”

Java Method Overloading

Method overloading means two or more methods share one name but differ in their parameters. The compiler picks the method that matches the arguments at a call.

Same name, different types

One plus method takes int values and the other takes double values. Each call picks the version that matches its arguments.

public class Main {
  static int plus(int a, int b) {
    return a + b;
  }

  static double plus(double a, double b) {
    return a + b;
  }

  public static void main(String[] args) {
    System.out.println(plus(2, 3));
    System.out.println(plus(2.5, 3.5));
  }
}

Same name, different counts

One plus method takes two values and the other takes three. The number of arguments at the call picks the version.

public class Main {
  static int plus(int a, int b) {
    return a + b;
  }

  static int plus(int a, int b, int c) {
    return a + b + c;
  }

  public static void main(String[] args) {
    System.out.println(plus(2, 3));
    System.out.println(plus(2, 3, 4));
  }
}

One name for two kinds of value

The show method has an int version and a String version. Each call below picks a different version.

public class Main {
  static void show(int value) {
    System.out.println("Number: " + value);
  }

  static void show(String text) {
    System.out.println("Text: " + text);
  }

  public static void main(String[] args) {
    show(7);
    show("Java");
  }
}

Example

public class Main {
  static int total(int a, int b) {
    return a + b;
  }

  static double total(double a, double b) {
    return a + b;
  }

  static int total(int a, int b, int c) {
    return a + b + c;
  }

  public static void main(String[] args) {
    System.out.println(total(10, 20));
    System.out.println(total(1.5, 2.5));
    System.out.println(total(10, 20, 30));
  }
}

Key points

  • Overloaded methods differ in parameter types or in parameter count.
  • A call with int arguments picks the int version.
  • A call with double arguments picks the double version.
  • The return type alone does not separate two overloads.

In this example, three methods share the name total. The first call passes two int values and returns 30. The second call passes double values and returns 4.0. The third call passes three int values and returns 60.

Note

Overloading lets one clear name serve several kinds of call.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Java Compiler

Exercise

What must differ between overloaded methods?