With the exception of java.lang.String
being treated as a special case1, Java does not allow you to define the behaviour of +
for arbitrary types, or indeed any other operator, as you can in some languages such as C++ or Scala. In other words, Java does not support operator overloading.
Your best bet is to build functions like add
&c. Appeal to precedent here: see how the Java guys have done it with BigInteger
, for example. Sadly there is no way of defining the precedence of your functions, so you have to use very many parentheses to tell the compiler how you want an expression to be evaluated. It's for this reason that I don't use Java for any serious mathematical applications as the implementation of even a simple equation quickly becomes an unreadable mess2.
1 Which in some ways does more harm than good: e.g. consider 1 + 2 + "Hello" + 3 + 4
. This compile time constant expression is a string type with the value 3Hello34
.
2 Note that C++ was used to model the gravitational lensing effects of the wormhole in the movie "Interstellar". I challenge anyone to do that in a language that does not support operator overloading! See https://arxiv.org/pdf/1502.03808v1.pdf