Why doesn't Java offer operator overloading?

2018-12-31 13:44发布

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?

15条回答
像晚风撩人
2楼-- · 2018-12-31 14:44

Check out Boost.Units: link text

It provides zero-overhead Dimensional analysis through operator overloading. How much clearer can this get?

quantity<force>     F = 2.0*newton;
quantity<length>    dx = 2.0*meter;
quantity<energy>    E = F * dx;
std::cout << "Energy = " << E << endl;

would actually output "Energy = 4 J" which is correct.

查看更多
泪湿衣
3楼-- · 2018-12-31 14:47

Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.

However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.

// a = b + c
Complex a, b, c; a = b.add(c);
查看更多
孤独总比滥情好
4楼-- · 2018-12-31 14:48

Groovy has operator overloading, and runs in the JVM. If you don't mind the performance hit (which gets smaller everyday). It's automatic based on method names. e.g., '+' calls the 'plus(argument)' method.

查看更多
登录 后发表回答