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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 01-Aug-2019 12:19:08
Advertisements