Java does not support direct operator overloading as it is implemented in C++, for example. Historically, this limitation was introduced to simplify code readability and reduce ambiguity: Bjarne Stroustrup (the creator of C++) and James Gosling (the creator of Java) discussed this issue, and in Java it was decided not to allow developers to define their own operator behavior for their classes.
The problem of operator overloading is that excessive freedom in defining arithmetic and logic for user-defined classes can lead to hard-to-track bugs and decreased code readability, especially in large teams.
The solution is to prohibit user-defined operator overloading. However, Java supports method overloading within its classes, and operator behavior can be mimicked through explicitly defined methods (e.g., .add(), .equals(), .compareTo(), etc.).
Code example:
public class Vector2D { private final int x, y; public Vector2D(int x, int y) { this.x = x; this.y = y; } public Vector2D add(Vector2D other) { return new Vector2D(this.x + other.x, this.y + other.y); } } Vector2D v1 = new Vector2D(2, 3); Vector2D v2 = new Vector2D(1, 4); Vector2D sum = v1.add(v2); // instead of v1 + v2
Key features:
Can you overload the operator "+" in Java for your class to add objects?
Answer: No, Java does not support user-defined overloading of arithmetic operators for user-defined classes. The exception is only made for strings: the operator "+" invokes concatenation through StringBuilder.
If you define the method equals(), will the operator "==" work as value comparison?
Answer: No, the operator "==" compares references to objects, not their content. To correctly compare values, the overridden equals() should be used.
String a = new String("hello"); String b = new String("hello"); System.out.println(a == b); // false System.out.println(a.equals(b)); // true
Are there exceptions where a standard operator behaves differently for non-standard classes?
Answer: "Special" behavior in Java is only implemented for String with the operator "+" and for primitive types (automatic promotion and unboxing). For other classes, operators behave normally (i.e., are not overloaded).
A young developer wrote a class Money and started comparing two objects using "==", believing they would compare by values. Because of this, errors arose in equality checks that only manifested in production.
Pros:
Cons:
In the project, a custom class Vector was written, all arithmetic operations were implemented explicitly, the operator == was not used for objects, and the documentation described the semantics of method operations.
Pros:
Cons: