Operator overloading in Java

前端 未结 10 1747
独厮守ぢ
独厮守ぢ 2020-11-21 23:51

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.

相关标签:
10条回答
  • 2020-11-22 00:42

    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++

    0 讨论(0)
  • 2020-11-22 00:42

    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.

    0 讨论(0)
  • 2020-11-22 00:46

    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.

    0 讨论(0)
  • 2020-11-22 00:47

    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.

    0 讨论(0)
提交回复
热议问题