views:

392

answers:

8

Why doesn't Java need operator overloading? Is there any way it can be supported in Java?

+6  A: 

Java only allows arithmetic operations on elementary numeric types. It's a mixed blessing, because although it's convenient to define operators on other types (like complex numbers, vectors etc), there are always implementation-dependent idiosyncracies. So operators don't always do what you expect them to do. By avoiding operator overloading, it's more opaque which function is called when. A wise design move in some people's eyes.

Sanjay Manohar
That is almost true, since it defines addition on char and string types.
Jonathan Allen
oh yeah, thanks!
Sanjay Manohar
@Jonathan Allen: that's so annoying! "We Do It Because We Can. Mere Mortals Such As The Likes Of You Shalt Not Meddle In Our Affairs."
aib
They only forgot BigInteger and BigDecimal :(
Hiro2k
You mean "more transparent", not "more opaque".
Darron
@aib: What's worse is they got it wrong. Both C# and Java use + for both addition and concatenation so we get weird type coercion bugs. They very same bugs that Visual Basic solved half a decade before Java was created by splitting them into two operators.
Jonathan Allen
+7  A: 

Java doesn't "need" operator overloading, because no language needs it.

a + b is just "syntactic sugar" for a.Add(b) (actually, some would argue that a.Add(b) is just syntactic sugar for Add(a,b))

James Curran
According to Java naming conventions, the method `add` should not be capitalized.
Erick Robertson
I wasn't speaking of Java specifically, but for languages in general. For example, in Java, you can't have the nonmember function Add(a,b)
James Curran
You can have a static method, which is essentially the same.
starblue
I thought a.Add(b) was (not exactly) syntactic sugar for call(a.Add,(b))
Roman A. Taycher
+1  A: 

This related question might help. In short, operator overloading was intentionally avoided when Java was designed because of issues with overloading in C++.

Scala, a newer JVM language, has a syntax that allows method overloading that functions very much like operator overloading, without the limitations of C++ operator overloading. In Scala, it's possible to define a method named +, for example. It's also possible to omit the . operator and parentheses in method calls:

case class A(value: Int) {
   def +(other: A) = new A(value + other.value)
}

scala> new A(1) + new A(3)                                                           
res0: A = A(4)
Aaron Novstrup
A: 

Java doesn't support operator overloading (one reference is the Wikipedia Operator Overloading page). This was a design decision by Java's creators to avoid perceived problems seen with operator overloading in other languages (especially C++).

GreenMatt
A: 

Check Java Features Removed from C and C++ p 2.2.7 No More Operator Overloading.

There are no means provided by which programmers can overload the standard arithmetic operators. Once again, the effects of operator overloading can be just as easily achieved by declaring a class, appropriate instance variables, and appropriate methods to manipulate those variables. Eliminating operator overloading leads to great simplification of code.

Incognito
A: 

It's not that java doesn't "need" operator overloading, it's just a choice made by its creators who wanted to keep the language more simple.

Colin Hebert
A: 

Java does not support operator overloading by programmers. This is not the same as stating that Java does not need operator overloading.

Operator overloading is syntactic sugar to express an operation using (arithmetic) symbols. For obvious reasons, the designers of the Java programming language chose to omit support for operator overloading in the language. This declaration can be found in the Java Language Environment whitepaper:

There are no means provided by which programmers can overload the standard arithmetic operators. Once again, the effects of operator overloading can be just as easily achieved by declaring a class, appropriate instance variables, and appropriate methods to manipulate those variables. Eliminating operator overloading leads to great simplification of code.

In my personal opinion, that is a wise decision. Consider the following piece of code:

String b = "b";
String c = "c";
String a = b + c;

Now, it is fairly evident that b and c are concatenated to yield a. But when one consider the following snippet written using a hypothetical language that supports operator overloading, it is fairly evident that using operator overloading does not make for readable code.

Person b = new Person("B");
Person c = new Person("C");
Person a = b + c;

In order to understand the result of the above operation, one must view the implementation of the overloaded addition operator for the Person class. Surely, that makes for a tedious debugging session, and the code is better implemented as:

Person b = new Person("B");
Person c = new Person("C");
Person a = b.copyAttributesFrom(c);
Vineet Reynolds
"[...] it is fairly evident that using operator overloading does not make for readable code." I wonder what kind of a language we'd be left with if we removed every feature that could be abused.
Aaron Novstrup
@anovstrup, I guess that would be a somewhat verbose yet understandable language with scope for committing fewer mistakes. I prefer languages that do not allow me to do this - #define private public (or their variants thereof).
Vineet Reynolds
@Vineet: Neither C nor C++ allows that, IIRC. I think it's undefined behavior under both standards.
bcat
I've always hated the logic that "because a bad programmer can use this functionality to write bad code, this functionality is bad". There are plenty of cases where operators in the code would be far clearer than method names. Knowing when to use operator overload and when not to is just one sign of a better programmer. You could just as easily say "being able to have two methods with the same name is bad, because someone might name all their methods the same name even if they do something different".
RHSeeger
@bcat, well undefined behavior under standards have never prevented people from getting clever with macros or other aspects of languages that were originally introduced to help programmers write better code.
Vineet Reynolds
@downvoter While I disagree with Vineet (I prefer a language that enables the good programmer to express his intent efficiently to one that coddles the bad programmer), I don't think this answer deserves a downvote. Whether we agree with the Java designers or not, this argument *is* one of the reasons that Java does not support operator overloading.
Aaron Novstrup
@RHSeeger, knowing when to use operator overload is good in hindsight. Not when you have to debug code written by a self-aggrandizing programmer. Writing readable code implies that you respect the time others spend on reading, debugging and eventually using your code.
Vineet Reynolds
@Vineet, Bad programmers will write bad code in any language. Sure, some language features make it easier or harder, but those same language features can have the exact opposite effect for good programmers (making code clearer used by a good programmer vs uglier used by a bad programmer). Just because people are injured in car accidents doesn't mean we should all be riding horses.
RHSeeger
@RHSeeger, well, last time I checked people wanting safe cars chose ones with air bags and all the other safety features. We don't need to ride horses, but the extra safety is worth it :-)
Vineet Reynolds
A: 

No language needs operator overloading. Some believe that Java would benefit from adding it, but its omission has been publicized as a benefit for so long that adding it is almost certainly politically unacceptable (and it's only since the Oracle buyout that I'd even include the "almost").

The counterpoint generally consists of postulating some meaningless (or even counterintuitive) overload, such as adding together two employees or overloading '+' to do division. While operator overloading in such languages as C++ would allow this, lack of operator overloading in Java does little to prevent or even mitigate the problem. someEmployee.Add(anotherEmployee) is no improvement over someEmployee + anotherEmployee. Likewise, if myLargeInteger.Add(anotherLargeInteger) actually does division instead of addition. At least to me, this line of argument appears thoroughly unconvincing at best.

There is, however, another respect in which omitting operator overloading does (almost certainly) have a real benefit. Its omission keeps the language easier to process, which makes it much easier (and quicker) to develop tools that process the language. Just for an obvious example, refactoring tools for Java are much more numerous and comprehensive than for C++. I doubt that this can or should be credited specifically and solely to support for operator overloading in C++ and its omission in Java. Nonetheless, the general attitude of keeping Java simple (including omission of operator overloading) is undoubtedly a major contributing factor.

Jerry Coffin
Try doing extensive work with BigInteger and you may start to come around to the idea that maybe all operator overloading isn't bad.
Jherico
I doubt operator overloading is much harder to parse if you force spaces(ie don't allow "a+b" only "a + b")
Roman A. Taycher