Can we overload a method based on different return type but same argument type and number, 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 division(int a, int b){
      int result = a/b;
      return result;
   }
   public double division (float a, float b){
      double result = a/b;
      return result;
   }
}

Overloading with same arguments and different return type −

No, you cannot overload a method based on different return type but same argument type and number in java.

In overloading it is must that the both methods have −

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

The return type doesn’t matter. If they don’t have different parameters, they both are still considered as same method and a compile time error will be generated.

Example

In the following example we are trying to overload two methods: They have same name (division) same parameters (two integers).

class Test{
   public int division(int a, int b){
      int result = a/b;
      return result;
   }
   public double division (int a, int b){
      double result = a/b;
      return result;
   }
}

Compile time error

If you try to compile the above program, since the parameters are not different Java compiler considers them as same methods and generates the following error.

OverloadingExample.java:6: error: method division(int,int) is already defined in class Test
public static double division (int a, int b){
                     ^
1 error
raja
Published on 08-Jul-2019 15:40:00
Advertisements