So here is my question. Since I learnt Java, I have been aware that arithmetic overflow and underflow can exist and java compiler will not complain it to you. Now I come up with a Operation class which has "overflow safe" integer +, -, * methods in it. So that if the calculation does overflow, it will throw arithmetic exception.
public final class Operation{
public static int aDD (int a, int b) {
//do something
if (overflow) {
throw ArithmeticException("Integer Addition Overflow");
}
return a + b;
}
public static int sUB (int a, int b) {
//do something
if (overflow) {
throw ArithmeticException("Integer Subtraction Overflow");
}
return a - b;
}
public static int mUL (int a, int b) {
//do something
if (overflow) {
throw ArithmeticException("Integer Multiplication Overflow");
}
return a * b;
}
public static long aDD (long a, long b) {
//do something
if (overflow) {
throw ArithmeticException("Long Addition Overflow");
}
return a + b;
}
public static long sUB (long a, long b) {
//do something
if (overflow) {
throw ArithmeticException("Long Subtraction Overflow");
}
return a - b;
}
public static long mUL (long a, long b) {
//do something
if (overflow) {
throw ArithmeticException("Long Multiplication Overflow");
}
return a * b;
}
}
I want to override the original arithmetic operators in Java. So that I don't need to type int c = Operation.aDD(a, b);
to use the "overflow safe" arithmetic operations. Instead, I only need to type int c = a + b;
However, I was told user defined operator overriding is not possible in Java. So, is there anyway to achieve the same result without overriding operator in Java. Anyway of doing so is acceptable, including mixing Java and C++ code.(Note that all my code is written in Java for now. But I think I can convert it to other language using a converter. Although it is not guaranteed to be bug-free.) My only goal is to allow my older program to use the "overflow safe" arithmetic operations without having to re-factor all the a + b
into Operation.aDD(a, b)
.
Thanks a lot!