Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

2.5. Operator overloading in Java

Not only does Java not support operator syntax for objects, but Java insiders vigorously disapprove of all operator overloading. Here’s a typical explanation:

  • “. . . the language designers decided (after much debate) that overloaded operators were a neat idea, but that code that relied on them became hard to read and understand.8

Those language designers must have felt that

totalPrice += quantityOrdered * unitPrice;
if (totalPrice > creditLimit) . . .

is harder to read and understand than

totalPrice.addSet(unitPrice.mpy(quantityOrdered));
if(totalPrice.greaterThan(creditLimit)) . . .

Many experienced application programmers express amazement, mild regret, or stern condemnation when they discover this, but whether or not we agree with the language designers’ choice, we still have to accept it and work around it.

Of course, programs still have to do arithmetic on numeric objects and compare numeric objects. We must therefore define named functions to take the place of operator syntax. This book uses the following mnemonics for those functions:

C++ operator

Java equivalent

− a

a.minus ()

a = b;

a.set(b)

a * b

a.add(b)

a − b

a.sub(b)

a * b

a.mpy(b)

a / b

a.div(b)

a % b

a.mod(b)

a *= b

a.addSet(b)

a −= b

a.subset (b)

a *= b

a.mpySet(b)

a /= b

a.divSet (b)

a %= b

a.modSet(b)

a == b

a.equals (b)

a < b

a.less Than (b)

a > b

a.greaterThan (b)

Problems and exercises

2.5-1 We provided equivalents for only three of the six possible Boolean operators. Is that acceptable? Advisable? Why?

2.5-2 Note that the equals function described above is not the one inherited from Object and conventionally overridden by other Java classes. In what ways is it different? Why do we need both? What about Java’s conventional compareTo function and Comparable interface?

  • + Share This
  • 🔖 Save To Your Account