Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java cannot overload any operators. Why? [duplicate]

Possible Duplicate:
Java operator overload

In c++, we can perform the operator overloading. But Java is also a Object oriented language. So why java doesn't support overloading?

like image 624
user315463 Avatar asked Apr 13 '10 12:04

user315463


People also ask

Why operator overloading is not possible in Java?

Java doesn't allow user defined operator overloading because if you allow programmer to do operator overloading they will come up with multiple meanings for same operator which will make the learning curve of any developer hard and things more confusing and messing.

Why we Cannot overload operators?

These operators cannot be overloaded because if we overload them it will make serious programming issues. For an example the sizeof operator returns the size of the object or datatype as an operand. This is evaluated by the compiler. It cannot be evaluated during runtime.

What are all the operators that Cannot be overloaded in Java?

Unlike C++, Java doesn't support operator overloading. Java doesn't provide freedom to programmers, to overload the standard arithmetic operators e.g. +, -, * and / etc.

Can we overload all operators?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function.


2 Answers

http://java.sun.com/docs/white/langenv/Simple.doc2.html

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.

The last statement is of course very subjective.

like image 177
Andreas Brinck Avatar answered Nov 07 '22 14:11

Andreas Brinck


Actually, it does support operator overloading... of a very limited, built-in only nature. For instance "+" is overloaded for String's in addition to the usual arithmetic.

Of course, most people want to know why Java does not support user-defined operator overloading. :-) The simplest answer seems to be that the Java creators did not, at the time, see any clean way to add it to the language without making Java a mess (like C++) in the process.

like image 27
Venkat Avatar answered Nov 07 '22 12:11

Venkat