This is NOT homework.
Is it possible to write a generic method, something like this:
Not the prettiest solution ever, but if you rely in the following properties of every known implementation of Number (in the JDK):
You can implement it using reflection and using Generics to avoid having to cast the result:
public class Test {
@SuppressWarnings("unchecked")
public static T plusOne(T num) {
try {
Class> c = num.getClass();
Constructor> constr = c.getConstructor(String.class);
BigDecimal b = new BigDecimal(num.toString());
b = b.add(java.math.BigDecimal.ONE);
return (T) constr.newInstance(b.toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
System.out.println(plusOne(1));
System.out.println(plusOne(2.3));
System.out.println(plusOne(2.4E+120));
System.out.println(plusOne(2L));
System.out.println(plusOne(4.5f));
System.out.println(plusOne(new BigInteger("129481092470147019409174091790")));
System.out.println(plusOne(new BigDecimal("12948109247014701940917.4091790")));
}
}
The return is done using an apparently unsafe cast but given that you're using a constructor of the class of some T or child of T you can assure that it will always be a safe cast.