As Louis Wasserman pointed out, there is no way to do this in Java. However, a solution can be presented by using some not-so-tricky programming. Let's start with a solution that I like: SylvainL's answer to the question. However, I believe we could go one step back and handle every type of Number
. If you look at the Java API, you can note that any subclass of Number
has to override a couple of abstract methods; namely, intValue() (as well as others). Using these methods, we can utilize polymorphism to its true potential. Taken the class we have from SylvainL's answer, we can produce a new class as such:
public final class EveryNumberClass<E extends Number>
{
public static int add(E x, E y)
{
return x.intValue() + y.intValue();
}
public static int subract(E x, E y)
{
return x.intValue() - y.intValue();
}
}
These operations could be expanded to multiplication and division, and while not limited to Integer
s, could be used to take in any Number
and express the appropriate behavior given an operation. And while the behavior of the intValue()
method may not return an integer representation of the Number
, it most certainly does (I looked in the source code for most numbers, including the atomic ones and the math ones). The only issue will occur when unexpected behavior is returned from intValue()
, which may happen with atomic numbers, user defined Number
s, or when big numbers are forced to shrink. If those are concerns for your project (or for your library), I would consider using long
values, or referring to SylvainL's answer.