V
V
Vasily Demin2018-09-23 16:24:26
Java
Vasily Demin, 2018-09-23 16:24:26

How to apply arithmetic operations to variables whose type is inherited from Number in java?

There is a generic class whose type variable extends the Number class. It is necessary to perform arithmetic operations on variables of type T. There was an option to apply operations to their double values, and then create a new instance of Number. But it turned out to be non-working: after applying the operation, only a double value could be extracted from the new Number instance.

class Sum<T extends Number> {
    private T t1, t2;
    Sum(T t1, T t2) {
        this.t1 = t1;
        this.t2 = t2;
    }

    public T sum() {
        return (T)(new Double(t1.doubleValue() + t2.doubleValue());
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Iloveski, 2018-09-24
@includedlibrary

Since it is written, it is impossible, at most, you can write a generic interface and write implementations for the desired types, for example

public class TestTask<T extends Number> {

    private Calc<T> calc;

    private T t1;

    private T t2;

    public TestTask(T t1, T t2) {
        this.t1 = t1;
        this.t2 = t2;
    }

    public T sum(T a, T b) {
        return calc.sum(a, b);
    }
}

interface Calc<T extends Number> {
    T sum(T a, T b);
}

class DoubleCalc implements Calc<Double> {
    @Override
    public Double sum(Double a, Double b) {
        return a+b;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question