- 2.1. Our emphasis
- 2.2. The basic goal—a major difference between C++ and Java
- 2.3. Constructors and destructor
- 2.4. Operator overloading in C++
- 2.5. Operator overloading in Java
- 2.6. Flow-control constructs
- 2.7. Manipulating character strings in C++
- 2.8. Canonical class structure
- 2.9. Overcoming macrophobia
- 2.10. Program readability
- 2.11. Error detection and exceptions
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?