简体   繁体   中英

How does the increment operator work on an Integer instance if Java doesn't support operator overloading?

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?

This is the sequence of operations that are performed when you call the increment operator on an Integer object:

  1. Integer wrapper object is unboxed to an int primitive (using the intValue() method).
  2. Primitive is incremented.
  3. Incremented primitive is autoboxed to an 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM