Can you overload the plus operator in Java, and if not, how do you express addition on your own types?
No, Java does not let you overload the plus operator. You cannot write a + b for your own type and have the compiler work it out. You write a method with a name of your own instead.
public class Main {
public static void main(String[] args) {
Vector a = new Vector(3, 4);
Vector b = new Vector(1, 2);
Vector sum = a.add(b);
System.out.println(sum); // Vector[x=4, y=6]
}
}
And here is the class.
public class Vector {
private final int x;
private final int y;
public Vector(int x, int y) {
this.x = x;
this.y = y;
}
public Vector add(Vector other) {
return new Vector(x + other.x, y + other.y);
}
public double length() {
return Math.sqrt(x * x + y * y);
}
@Override
public String toString() {
return "Vector[x=" + x + ", y=" + y + "]";
}
}
So how do you express addition on your own types? You use a method with a good name, and you give it a name that reads well at the call site.
the name how it reads
-------------------------- ----------------------------------
add a.add(b)
plus a.plus(b)
sum a.sum(b)
combine a.combine(b)
And the reason Java does it this way is worth knowing about, because it explains a lot about the language. The plus operator is built into the language and the compiler knows what it means for the primitive types. If you could redefine it for your own types then a + b could mean different things in different places, and the readability of the language would suffer. So Java keeps the operators for the built-in types and lets you name your own operations.
And there is one more thing worth knowing about. Java does let you use the plus operator with a string, and that is a special case in the language. So "total: " + total works, and the compiler turns it into a string concatenation. And if one side of the plus is a string then the whole thing is a concatenation, which is a common source of bugs.
int total = 5;
System.out.println("total: " + total); // total: 5
System.out.println("total: " + total + 1); // total: 51, not 6
So the rule to remember is this. Name your own operation, and make the name read well at the call site.
The last question in this topic is about which operators Java lets you overload.