If I change the return type, will the method gets overloaded in java?


When a class has two or more methods by the same name but different parameters, at the time of calling, based on the parameters passed, respective method is called (or respective method body will be bonded with the calling line dynamically). This mechanism is known as method overloading.

Example

class Test{
   public int addition(int a, int b){
      int result = a+b;
      return result;
   }
   public int addition (int a, int b, int c){
      int result = a+b+c;
      return result;
   }
   public static void main(String args[]){
      Test t = new Test();
      System.out.println(t.addition(25, 36));
      System.out.println(t.addition(25, 50, 25));
   }
}

Output

61
100

Overloading based on different return type

In overloading it is must that the both methods have −

  • same name.
  • different parameters (different type or, different number or both).

Same return type is not mandatory. Therefore, you can overload methods with different return types if they have same name and different return types.

Example

In the following example we are trying to overload two methods: They have same name (addition) different parameters and different return types.

class Test{
   public int addition(int a, int b){
      int result = a+b;
      return result;
   }
   public float addition (float a, float b){
      float result = a+b;
      return result;
   }
   public static void main(String args[]){
      Test t = new Test();
      System.out.println(t.addition(25, 36));
      System.out.println(t.addition(100.25f, 36.1f));
   }
}

Output

61
136.35

Updated on: 02-Jul-2020

814 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements