I want to make good use of polymorphism in java when implementing math operations between objects of math classes.
I got from the answers in How to add two java.lang.Numbers?
that the general solution when using java.lang.Number is to know or check the real objects class and make the appropriate hardcoded conversion to float, int, etc.
But this approach actually is not very object oriented. The java language designers chose to give the java.lang.Number
class and its derivatives a set of methods floatValue()
, intValue()
and so on.
In light of this, Is my proposed approach, below, not going to work?.
To implement mathematical operations in a seamless way I want to to rewrite the Number class Hierarchy to allow to do something like this:
MyNumber a = b.getValue() + c.getValue();
where the real type of b
and c
don't matter
The base class would be:
public abstract class MyNumber {
protected Object mValue;
public abstract <N> N getValue();
}
And, for example, my integer class would look like:
public class MyInteger extends MyNumber {
public MyInteger(int value) {
mValue = value;
}
@Override
public Integer getValue() {
return (Integer) mValue;
}
}
and similarly for MyFloat, MyDouble, etc.