Search code examples
javaclassobjectadditioncalculator

How use Object while creating Generic class?


I want to create a generic class of Object.

class Calculator<Object> {

         // addition function for addition of two numbers (Integer , Float)

    Object addition(Object first, Object second)
    {
        
        return  ;    //Should return as Object

    }
}

Thanks in Advance... (P.S. NOT going to use it in project......Asking just for my conceptual clarity)


Solution

  • If you want to define a generic class, better use a capital letter as the generic type name, for example

    class Calculator<T> {
        T addition(T first, T second) {
            //how to add two generic objects?
        }
    }
    

    Maybe you don't want to add two arbitrary objects, but Numbers

    class Calculator<T extends Number> {
        T addition(T first, T second) {
            return first + second; //does not compile!
        }
    }
    

    The sad news is that Number does not have an add method, and you can't just use the + operator. Maybe you can define an abstract class or interface

    interface Calculator<T extends Number> {
        default T addition(@Nullable T first, @Nullable T second) {
            if (first == null || second == null) {
                return first == null ? second : first;
            }
            return nonNullAddition(first, second);
        }
        
        T nonNullAddition(@NotNull T first, @NotNull T second);
    }
    

    and implement for the cases you need

    class IntCalculator implements Calculator<Integer> {
        @Override
        public Integer nonNullAddition(@NotNull Integer first, @NotNull Integer second) {
            return first + second;
        }
    }
    
    class BigDecimalCalculator implements Calculator<BigDecimal> {
        @Override
        public BigDecimal nonNullAddition(@NotNull BigDecimal first, @NotNull BigDecimal second) {
            return first.add(second);
        }
    }
    

    Yet, this might be cumbersome. If you don't care about precision, you can cast (more properly it is a widening conversion) everything to double; if you care about precision you can use BigDecimal.

    class Calculator {
        public double addition(double first, double second) {
            return first + second;
        }
    
        public BigDecimal addition(BigDecimal first, BigDecimal second) {
            return first.add(second);
        }
    }
    

    and use it in the following way:

    double f = 1.0;
    int i = 2;
    Calculator calc = new Calculator();
    double sum = calc.addition(f, i);
    BigDecimal preciseSum = calc.addition(new BigDecimal(f), new BigDecimal(i));