Java Method Overloading

In java, if any two or more methods have the same name but with different parameters and different return type then its called as method overloading.

Here the methods with same name and different parameters are considered differently.

Example

void add() {....}
int add(int a, int b) { .... }
float add(float a, float b) {....}

In the above example, we have 4 different functions with same name but with different parameters and return type.

Example program for method overloading

class Main {

  public void add(){
      int a=10,b=20;
      System.out.println("Function with no params");
      System.out.printf("Sum of %d and %d is %d",a,b,a+b);
      System.out.println();
  }

  public int add(int a, int b) {
      System.out.println("Function with 2 params as int");
    // return the sum of a & b
    return  a + b;
  }
  
  public void add(double a, double b) {
    System.out.println("Function with 2 params as double");
    System.out.printf("Sum of %.2f and %.2f is %.2f",a,b,a+b);
    System.out.println();
  }
  

  public static void main(String[] args) {
    
    int number1 = 20;
    int number2 = 10;

    // create an object of Main
    Main obj = new Main();
    obj.add();
    obj.add(1.4,30.5);
    int result = obj.add(number1, number2);
    System.out.printf("Sum of %d and %d is %d",number1,number2, result);
  }
}

In the above program, we have 3 method with same name add() method.

add() - This method does not take any parameter but adds two local variables and print the result. This type does not take parameter and does not return anything.

int add(int a, int b) - This method takes 2 int variable as parameter, add them and return the int as response.

void add(double a, double b) - This method takes 2 double variable as parameter, add them and print the result. This does not return anything.

Each type has different usecases. We can use any of these method based on the requirement. Best approach will be create methods with parameter and return type.


Most Read