user3584264
user3584264

Reputation: 41

Operator definition in java

int i = 10;
i++; // it ok primitive value can use ++.

Integer integer = 10;
integer++; // how it can use ++

MyClass myClass  = new MyClass();
myClass++; // then why myclass can't use ++.

Upvotes: 0

Views: 126

Answers (3)

chrisb2244
chrisb2244

Reputation: 3001

From the Link provided in a comment by Konstantin V. Salikhov,

Integer has a defined method to return an int, which then has the ++ operator defined. MyClass has no ++ operator, hence myClass++; is invalid

The method in question goes like:

Integer myInteger = 10;
myInteger.intValue++;

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

Operator overloading in Java has a description (as to it being not allowed) at Operator overloading in Java

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234725

C++ has the ability to overload operators. The Java language considers this to be open to too much abuse (overloaded operators can be obfuscating) so it was never incorporated into Java.

Therefore, you can't write myClass++ as the syntax is not available to specify that operation.

But ++ does work on a selection of non-primitives. The mechanism exploited is called autoboxing. (Essentially the underlying plain-old-data type is extracted from the boxed type, incremented then re-boxed to the original reference type).

Somewhat related to this is the ability to apply += and + to java.lang.String instances. Simply put, this is a special case. Although fully aware of the risk of downvotes I regard this as one of the worst kludges in Java, particularly += which will create a new instance of a string (as strings themselves are immutable), and many Java programmers will be unaware of the effect this has on memory.

Upvotes: 4

Aaron Sung
Aaron Sung

Reputation: 11

It is because of Java's autoboxing feature which is added in Java 1.5 The compiler will convert the statment as follow

Integer integer = 10;
integer.iniValue++;

You can try to add the compiler flag "javac -source 1.4" and it will return an error

Upvotes: 1

Related Questions