Reputation: 954
I read that Java does not support operator overloading. Then it made me wonder how you can use the increment operator on an instance of the Integer class.
Integer number = new Integer(10);
System.out.println(++number);
The above code compiles fine, without error. But let's say I made my own class, with only one member variable (an integer), and tried to use the increment operator. It would give me a compiler error. Why is this?
Upvotes: 0
Views: 1279
Reputation: 97120
This is the sequence of operations that are performed when you call the increment operator on an Integer
object:
Integer
wrapper object is unboxed to an int
primitive (using the intValue()
method).Integer
wrapper object.So, in effect, the operator is actually applied to an int
primitive, and not to an object. This behavior is only defined for objects of the primitive wrapper classes, and there is no way to make your own classes behave in a similar way.
See here for more info about autoboxing and unboxing.
Upvotes: 5