I like Java but I can’t understand why it still doesn’t have operator overloading.
Everyday operator overloading
Every Java object has two (and more) methods:
String toString(): Returns a string representation of the object.
boolean equals(Object obj): Indicates whether some other object is “equal to” this one.
So basically if you want to check whether Object a equals Object b, you type a.equals(b). But wait a second, there’s an operator == which checks if two integers are equal, so why not Objects? Well, because Java doesn’t know operator overloading.
And you can say whatever you want, but typing a == b is way more intuitive than typing a.equals(b).
Similar with toString(). Why not just cast this Object to a String object? (String)a is at least a little bit nicer to read than a.toString().
Any official statement?
I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++.
James Gosling. (source)
So it people abuse a programming language feature you should not implement it? This is nonsense.
It’s like saying exceptions are evil because someone could abuse them as a return value.
Yeah. Someone could, someone will, but everyone who cares won’t use his code.
Java has operator overloading!
Yes, Java uses operator overloading. But unfortunately it can’t be influenced by the user.
Let’s see an example:
int a = 5, b = 10;
int c = a + b; // c = 15
String s = "foo", p = "bar";
String o = s + p; // o = "foobar"
So Java declares two completely different meanings to the + operator. It can’t be that evil if the Java Standard does it.
Style comparison
Let’s compare some code to see what looks better.
// Java
SomeComplexType a,b;
if(a.equals(b))
foo();
Data d1,d2;
if(d1 < d2)
bar();
Vector<String> v = /* ... create and fill ... */
String s = v.elementAt(42);
compared to
// C++
SomeComplexType a,b;
if(a == b)
foo();
Date d1,d2; // Class overloading comparison operators
if(d1 < d2)
bar();
vector<string> v; /* fill */
string s = v[42];
Clearly if you re
There’s more than mumerical types
Whenever people argument about liking operator overloading others will counter with “yeah, but it’s only useful for numerical types”. Wrong.
Here are some examples:
- Every comparable class: overloading == (and !=)
- libpqxx (Postgres C++ library): [] to access rows/columns in a SELECT result.
- glibmm: various overloadings for glib::ustring. (e.g. glib::ustring s = “foo”)
- Various boost libraries for various reasons.
- many many more
So why is operator overloading important? Well, it uses the programmers knowledge about operators and appends them to other objects. Therefore if the programmer knows that comparing two integers can be accomplished by typing a == b it should also be able to be used to compare any other object.
I like Java but I can’t understand why it still doesn’t have operator overloading. Everyday operator overloading Every Java object has two (and more) methods: String toString(): Returns a string...