Java Tutorial Java Advanced Java References

Java - Method Overloading



With method overloading feature in Java, two or more methods can have the same name but different parameters. It allows the programmer to write methods to perform conceptually the same thing on different types of data without changing the name.

Example:

In the example below, three methods with the same name MyMethod are created. First method takes two integer numbers as arguments and returns sum of these numbers. The second method takes two float numbers as arguments and returns sum of these numbers. The third method takes three integer numbers as arguments and returns sum of these numbers.

public class MyClass {
  static int MyMethod(int a, int b) {
    return a + b;
  }

  static float MyMethod(float a, float b) {
    return a + b;
  }

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

  public static void main(String[] args) {
    int a = 100, b = 10, c = 1;
    float p = 500.5f, q = 50.05f;

    System.out.print("MyMethod(int, int) is used. Result: "); 
    System.out.print(MyMethod(a,b)+"\n"); 
    System.out.print("MyMethod(float, float) is used. Result: "); 
    System.out.print(MyMethod(p,q)+"\n");
    System.out.print("MyMethod(int, int, int) is used. Result: ");  
    System.out.print(MyMethod(a,b,c)+"\n");
  }
}

The output of the above code will be:

MyMethod(int, int) is used. Result: 110
MyMethod(float, float) is used. Result: 550.55
MyMethod(int, int, int) is used. Result: 111

❮ Java - Methods