10.2 Operator overloading


Operator overloading is a new concept to Java developers since Java doesn't allow operator overloading. [3] , [4]

[3] Some Java programmers may want to argue that the + operator in Java is a pseudo-overloaded operator when it is used for concatenating strings. This is a special case whereby the compiler actually decides if you are doing a numerical addition or a string concatenation depending on the operand types, and hence shows a little 'operator overloading' behavior.

[4] Operator overloading is a feature in C++ though.

In brief, operator overloading allows you to write special methods (called operators, or operator methods ) which are invoked when an overloaded operator is used to perform an operation on one or more operands. For example, you can overload the + operator so that you can 'add up' two objects of type Matrix ( Matrix may be a user -defined class which represents a matrix). The following statements will then make sense:

 Matrix m1 = new Matrix(); Matrix m2 = new Matrix(); // + operator overloaded to accept Matrix operands Matrix m3 = m1 + m2; 

Operator overloading is an elegant way of allowing programmers to perform 'operations' on classes in a more intuitive way. Java does not support operator overloading.

More information about operator overloading can be found in Chapter 22.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net