Search code examples
javamethodsoverloadingreturn-type

The relationship of overload and method return type in Java?


If there are two methods, they have different parameters, and their return types are different. Like this:

int test(int p) {
   System.out.println("version one");
   return p;
}

boolean test(boolean p, int q) {
   System.out.println("version two");
   return p;
}

If the return types are same, of course this is overload. But since the return types are different, can we regard this as overload still?


Solution

  • consider following points for overloading:

    1. First and important rule to overload a method in java is to change method signature. Method signature is made of number of arguments, type of arguments and order of arguments if they are of different types.

      public class DemoClass {
          // Overloaded method
          public Integer sum(Integer a, Integer b) {
              return a + b;
          }
      
          // Overloading method
          public Integer sum(Float a, Integer b) {  //Valid
              return null;
          }
      }
      
    2. Return type of method is never part of method signature, so only changing the return type of method does not amount to method overloading.

      public class DemoClass {
          // Overloaded method
          public Integer sum(Integer a, Integer b) {
              return a + b;
          }
      
          // Overloading method
          public Float sum(Integer a, Integer b) {     //Not valid; Compile time error
              return null;
          }
      }
      
    3. Thrown exceptions from methods are also not considered when overloading a method. So your overloaded method throws the same exception, a different exception or it simply does no throw any exception; no effect at all on method loading.

      public class DemoClass {
          // Overloaded method
          public Integer sum(Integer a, Integer b) throws NullPointerException{
              return a + b;
          }
      
          // Overloading method
          public Integer sum(Integer a, Integer b) throws Exception{  //Not valid; Compile time error
              return null;
          }
      }