1

While I understand the importance of method overloading, but I'm curious if its possible to write a single add function for the following code:

public class Add {

    public int add(int i, int j) {
        return i + j;
    }
    public double add(double i, double j) {
        return i + j;
    }
}
schwillr
  • 87
  • 6
  • what do you mean by single function? You can always remove the add function adding ints but remember the output will be a double value. – Vinay Prajapati Oct 11 '19 at 12:30

3 Answers3

-1

The other answer will not work, but if we modify it a little bit, it can work:

public Number add(Number i, Number j) {
    if(i instanceof Integer && j instanceof Integer) {
        return i.intValue() + j.intValue();
    } else if(i instanceof Double && j instanceof Double) {
        return i.doubleValue() + j.doubleValue();
    } //you can check for more number subclasses
    return null; //or throw and exception
}   

But this is so much uglier then overloading.

Gtomika
  • 845
  • 7
  • 24
-2

Instead of overloading, you can have a generic approach.

public static class Utils {

public static <T extends Number> Number multiply(T x, T y) {
    if (x instanceof Integer) {
        return ((Integer) x).intValue() + ((Integer) y).intValue();
    } else if (x instanceof Double) {
        return ((Double) x).doubleValue() + ((Double) y).doubleValue();
    }
    return 0;
   }
}

and use it like this

Utils.<Double>multiply(1.2, 2.4); // allowed
Utils.<Integer>multiply(1.2, 2.4); // not allowed
Utils.<Integer>multiply(1, 2); // allowed
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
-2

Of course it is possible. First of all, the double function can accept int values, so you can use that for both if you want. However, if you still want to achieve your goal, the best way is to use generics. Another way is to make your method accept a parent of both classes for example Object and then cast appropriately as shown below:

public class Add {

   enum ParamType {
       INT,
       DOUBLE
   }

   public static Object add(Object i, Object j, ParamType paramType) {
       if (paramType.equals(ParamType.INT)) {
           return (int) i + (int) j;
       } else {
           return (double) i + (double) j;
       }
   }

   public static void main(String[] args) {
       System.out.println(add(3.4, 5.2, ParamType.DOUBLE));
       System.out.println(add(3, 5, ParamType.INT));
   }
}
Gtomika
  • 845
  • 7
  • 24