Please can you tell me if it is possible to overload operators in Java? If it is used anywhere in Java could you please tell me about it.
Java does not allow operator overloading. The preferred approach is to define a method on your class to perform the action: a.add(b)
instead of a + b
. You can see a summary of the other bits Java left out from C like languages here: Features Removed from C and C++
Unlike C++, Java does not support user defined operator overloading. The overloading is done internally in java.
We can take +
(plus) for example:
int a = 2 + 4;
string = "hello" + "world";
Here, plus adds two integer numbers and concatenates two strings. So we can say that Java supports internal operator overloading but not user defined.
No, Java doesn't support user-defined operator overloading. The only aspect of Java which comes close to "custom" operator overloading is the handling of + for strings, which either results in compile-time concatenation of constants or execution-time concatenation using StringBuilder/StringBuffer. You can't define your own operators which act in the same way though.
For a Java-like (and JVM-based) language which does support operator overloading, you could look at Kotlin or Groovy. Alternatively, you might find luck with a Java compiler plugin solution.
Or, you can make Java Groovy and just overload these functions to achieve what you want
//plus() => for the + operator
//multiply() => for the * operator
//leftShift() = for the << operator
// ... and so on ...
class Fish {
def leftShift(Fish fish) {
print "You just << (left shifted) some fish "
}
}
def fish = new Fish()
def fish2 = new Fish()
fish << fish2
Who doesnt want to be/use groovy? :D
No you cannot use the compiled groovy JARs in Java the same way. It still is a compiler error for Java.