Why is method overloading not possible by changing the return type of the method only in java?

Java 8Object Oriented ProgrammingProgramming

Overloading is the mechanism of binding the method call with the method body dynamically based on the parameters passed to the method call.

If you observe the following example, it contains two methods with same name, different parameters and if you call the method by passing two integer values the first method will be executed and, if you call by passing 3 integer values then the second method will be executed.
It is not possible to decide to execute which method based on the return type, therefore, overloading is not possible just by changing the return type of the method.

Example

Live Demo

public class Sample{
   public int add(int a, int b){
      int c = a+b;
      return c;
   }
   public void add(int a, int b, int c){
      int z = a+b+c;
      System.out.println(z);
   }
   public static void main(String args[] ){
      Sample obj = new Sample();
      System.out.println(obj.add(40, 50));
      obj.add(40, 50, 60);
   }
}

Output

90
150
raja
Published on 08-Jan-2018 13:09:22
Advertisements