Reputation: 6202
I have spent hours researching this, and I'm still very confused.
I, like many others, searched this on Google and found this SO thread.
However, recently, a student in one of my programming courses told me that this wasn't true, and in fact, the instructor verified it. Hell, the entire class heard it, and no one contested him. He offered this link from Java.net as proof.
I said to him immediately, "That looks like JavaScript," but he pointed to this section:
class User {
List roles;
User() {
roles = new List();
}
operator +(Role newRole) {
this.roles.add(newRole);
}
}
main() {
User alice = new User();
Role adminUser = new Role("TIMESHEET_ADMIN", 3);
alice + adminUser;
print(alice.roles.length);
}
and told me that it was indeed Java. I, having no experience in JS couldn't tell, and he got away (for now), but I tried putting this into my IDE (IntelliJ), and I was assaulted by compiler errors. I didn't even know where to begin with fixing them, but the main thing was the cannot resolve symbol "operator"
.
I'm not looking here for any discussion on Java's built-in operator overloading, I am looking for a definitive answer on whether or not users in Java can overload operators themselves.
Upvotes: 2
Views: 3398
Reputation: 285405
The definitive answer is no, Java does not support operator overloading except for with String types. But more importantly, a larger answer to your question is that you should look in the one single document, the Java Language Specification or JLS that will answer this and any other similar question about what Java does or doesn't contain. Don't debate with anyone about maybes or ifs. Go look for yourself and satisfy for yourself that there is no such thing as operator overloading for Java except for the magical String type. It's all there in the JLS, and that's what it's for.
Upvotes: 12