Can you overload the plus operator in Java, and if not, how do you express addition on your own types?
Java does not let you redefine what the plus sign means. The arithmetic operators work on the primitive numeric types and on String concatenation, and there is no way to teach the compiler that plus on your own class should add two vectors.
public class Main {
public static void main(String[] args) {
Vector a = new Vector(3, 4);
Vector b = new Vector(1, 2);
System.out.println(a.plus(b));
System.out.println(a.times(2));
System.out.println(a);
}
}
class Vector {
final int x;
final int y;
Vector(int x, int y) { this.x = x; this.y = y; }
Vector plus(Vector other) { return new Vector(x + other.x, y + other.y); }
Vector times(int factor) { return new Vector(x * factor, y * factor); }
public String toString() { return "(" + x + "," + y + ")"; }
}The convention is to express the operation with a well-named method instead. The vector class offers plus and times, and the output shows both working: adding the two vectors produces 4,6, scaling produces 6,8, and the original vector is unchanged at 3,4 because the operations return new values rather than mutating.
The reason for the restriction is that operator overloading in Java is limited to the operators the language already defines for the built-in types, and the set of operators that can be redefined is fixed and small. There is no way to add a new operator or to overload an arbitrary method name as an operator.
The standard library does use this style. The BigInteger class offers add, multiply and subtract rather than operator symbols, and the Optional and Stream APIs follow the same convention of naming operations clearly. The design principle is that a named method reads better at the call site, because the reader sees what the operation is rather than guessing from a symbol.