Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading?
Isn't Complex a, b, c; a = b + c;
much simpler than Complex a, b, c; a = b.add(c);
?
Is there a known reason for this, valid arguments for not allowing operator overloading? Is the reason arbitrary, or lost to time?
Alternatives to Native Support of Java Operator Overloading
Since Java doesn't have operator overloading, here are some alternatives you can look into:
If anyone is aware of others, please comment, and I will add it to this list.
There are a lot of posts complaining about operator overloading.
I felt I had to clarify the "operator overloading" concepts, offering an alternative viewpoint on this concept.
Code obfuscating?
This argument is a fallacy.
Obfuscating is possible in all languages...
It is as easy to obfuscate code in C or Java through functions/methods as it is in C++ through operator overloads:
...Even in Java's standard interfaces
For another example, let's see the
Cloneable
interface in Java:You are supposed to clone the object implementing this interface. But you could lie. And create a different object. In fact, this interface is so weak you could return another type of object altogether, just for the fun of it:
As the
Cloneable
interface can be abused/obfuscated, should it be banned on the same grounds C++ operator overloading is supposed to be?We could overload the
toString()
method of aMyComplexNumber
class to have it return the stringified hour of the day. Should thetoString()
overloading be banned, too? We could sabotageMyComplexNumber.equals
to have it return a random value, modify the operands... etc. etc. etc..In Java, as in C++, or whatever language, the programmer must respect a minimum of semantics when writing code. This means implementing a
add
function that adds, andCloneable
implementation method that clones, and a++
operator than increments.What's obfuscating anyway?
Now that we know that code can be sabotaged even through the pristine Java methods, we can ask ourselves about the real use of operator overloading in C++?
Clear and natural notation: methods vs. operator overloading?
We'll compare below, for different cases, the "same" code in Java and C++, to have an idea of which kind of coding style is clearer.
Natural comparisons:
Please note that A and B could be of any type in C++, as long as the operator overloads are provided. In Java, when A and B are not primitives, the code can become very confusing, even for primitive-like objects (BigInteger, etc.)...
Natural array/container accessors and subscripting:
In Java, we see that for each container to do the same thing (access its content through an index or identifier), we have a different way to do it, which is confusing.
In C++, each container uses the same way to access its content, thanks to operator overloading.
Natural advanced types manipulation
The examples below use a
Matrix
object, found using the first links found on Google for "Java Matrix object" and "c++ Matrix object":And this is not limited to matrices. The
BigInteger
andBigDecimal
classes of Java suffer from the same confusing verbosity, whereas their equivalents in C++ are as clear as built-in types.Natural iterators:
Natural functors:
Text concatenation:
Ok, in Java you can use
MyString = "Hello " + 25 + " World" ;
too... But, wait a second: This is operator overloading, isn't it? Isn't it cheating???:-D
Generic code?
The same generic code modifying operands should be usable both for built-ins/primitives (which have no interfaces in Java), standard objects (which could not have the right interface), and user-defined objects.
For example, calculating the average value of two values of arbitrary types:
Discussing operator overloading
Now that we have seen fair comparisons between C++ code using operator overloading, and the same code in Java, we can now discuss "operator overloading" as a concept.
Operator overloading existed since before computers
Even outside of computer science, there is operator overloading: For example, in mathematics, operators like
+
,-
,*
, etc. are overloaded.Indeed, the signification of
+
,-
,*
, etc. changes depending on the types of the operands (numerics, vectors, quantum wave functions, matrices, etc.).Most of us, as part of our science courses, learned multiple significations for operators, depending on the types of the operands. Did we find them confusing, them?
Operator overloading depends on its operands
This is the most important part of operator overloading: Like in mathematics, or in physics, the operation depends on its operands' types.
So, know the type of the operand, and you will know the effect of the operation.
Even C and Java have (hard-coded) operator overloading
In C, the real behavior of an operator will change according to its operands. For example, adding two integers is different than adding two doubles, or even one integer and one double. There is even the whole pointer arithmetic domain (without casting, you can add to a pointer an integer, but you cannot add two pointers...).
In Java, there is no pointer arithmetic, but someone still found string concatenation without the
+
operator would be ridiculous enough to justify an exception in the "operator overloading is evil" creed.It's just that you, as a C (for historical reasons) or Java (for personal reasons, see below) coder, you can't provide your own.
In C++, operator overloading is not optional...
In C++, operator overloading for built-in types is not possible (and this is a good thing), but user-defined types can have user-defined operator overloads.
As already said earlier, in C++, and to the contrary to Java, user-types are not considered second-class citizens of the language, when compared to built-in types. So, if built-in types have operators, user types should be able to have them, too.
The truth is that, like the
toString()
,clone()
,equals()
methods are for Java (i.e. quasi-standard-like), C++ operator overloading is so much part of C++ that it becomes as natural as the original C operators, or the before mentioned Java methods.Combined with template programming, operator overloading becomes a well known design pattern. In fact, you cannot go very far in STL without using overloaded operators, and overloading operators for your own class.
...but it should not be abused
Operator overloading should strive to respect the semantics of the operator. Do not subtract in a
+
operator (as in "do not subtract in aadd
function", or "return crap in aclone
method").Cast overloading can be very dangerous because they can lead to ambiguities. So they should really be reserved for well defined cases. As for
&&
and||
, do not ever overload them unless you really know what you're doing, as you'll lose the the short circuit evaluation that the native operators&&
and||
enjoy.So... Ok... Then why it is not possible in Java?
Because James Gosling said so:
Please compare Gosling's text above with Stroustrup's below:
Would operator overloading benefit Java?
Some objects would greatly benefit from operator overloading (concrete or numerical types, like BigDecimal, complex numbers, matrices, containers, iterators, comparators, parsers etc.).
In C++, you can profit from this benefit because of Stroustrup's humility. In Java, you're simply screwed because of Gosling's personal choice.
Could it be added to Java?
The reasons for not adding operator overloading now in Java could be a mix of internal politics, allergy to the feature, distrust of developers (you know, the saboteur ones that seem to haunt Java teams...), compatibility with the previous JVMs, time to write a correct specification, etc..
So don't hold your breath waiting for this feature...
But they do it in C#!!!
Yeah...
While this is far from being the only difference between the two languages, this one never fails to amuse me.
Apparently, the C# folks, with their "every primitive is a
struct
, and astruct
derives from Object", got it right at first try.And they do it in other languages!!!
Despite all the FUD against used defined operator overloading, the following languages support it: Scala, Dart, Python, F#, C#, D, Algol 68, Smalltalk, Groovy, Perl 6, C++, Ruby, Haskell, MATLAB, Eiffel, Lua, Clojure, Fortran 90, Swift, Ada, Delphi 2005...
So many languages, with so many different (and sometimes opposing) philosophies, and yet they all agree on that point.
Food for thought...
Assuming Java as the implementation language then a, b, and c would all be references to type Complex with initial values of null. Also assuming that Complex is immutable as the mentioned BigInteger and similar immutable BigDecimal, I'd I think you mean the following, as you're assigning the reference to the Complex returned from adding b and c, and not comparing this reference to a.
This is not a good reason to disallow it but a practical one:
People do not always use it responsibly. Look at this example from the Python library scapy:
Here is the explanation:
Saying that operator overloading leads to logical errors of type that operator does not match the operation logic, it's like saying nothing. The same type of error will occur if function name is inappropriate for operation logic - so what's the solution: drop the ability of function usage!? This is a comical answer - "Inappropriate for operation logic", every parameter name, every class, function or whatever can be logicly inappropriate. I think that this option should be available in respectable programing language, and those that think that it's unsafe - hey no bothy says you have to use it. Lets take the C#. They drooped the pointers but hey - there is 'unsafe code' statement - program as you like on your own risk.
Some people say that operator overloading in Java would lead to obsfuscation. Have those people ever stopped to look at some Java code doing some basic maths like increasing a financial value by a percentage using BigDecimal ? .... the verbosity of such an exercise becomes its own demonstration of obsfuscation. Ironically, adding operator overloading to Java would allow us to create our own Currency class which would make such mathematical code elegant and simple (less obsfuscated).