Operator Overloading in Java

Author: Szymon Lipiński
Published at: 2011-06-27

C++ has got operator overloading. Java does NOT have. Java folks just say the operation overloding is really bad, that it provides bad abstraction and leads to very unreliable and difficult to manage code. That’s why Java doesn’t have operators overloading.

This is why I cannot check if BigDecimal is less than zero in the normal way:

    public something(BigDecimal price) {
        if (price < 0) {
            throw new IllegalArgumentException("Price cannot be less than 0");
        }
    }

Instead of the above simple code I just have to write this:

    public something(BigDecimal price) {
        if (price.compareTo(BigDecimal.ZERO) == -1) {
            throw new IllegalArgumentException("Price cannot be less than 0");
        }
    }

This is a kind of a nightmare, why use the compareTo function which returns that cryptic -1, 0, 1 values? I really want to have operator overloading in Java. The code will be much simpler.

Btw even PostgreSQL has operator overloading.

The comments are disabled. If you want to write something to me, you can use e.g. Twitter.