views:

201

answers:

5
+4  Q: 

Java = operator

Integer n = 5;  
System.out.println(n) // 5!

How can i reproduce this behavior in my classes?

+1  A: 

You can't overload the assignment operator in Java.

Ignacio Vazquez-Abrams
+9  A: 

You can't. This is called Autoboxing, and it is a special feature of some classes in Java to ease working with classes that represent primitive types like int.

AraK
its true you cant fake autoboxing, but you can write code that mimics what that code is likely compiled to. `Integer n = new Integer(5);` can easily be modified for whatever your needs are.
twolfe18
Autoboxing actually generates something more like `Integer.valueOf(5)`, rather than `new Integer(5)`. This is so some instances can be reused.
Laurence Gonsalves
+1  A: 

You can't overload operators in Java. The guys at Sun decided they would do it for a few classes, but they won't let you do it yourself.

zneak
A: 

The assignment operator cannot be overloaded in java. You need to look at other languages such as C++. I don't know if you can do it even there for the assignment operator.

fastcodejava
You can overload the assignment operator in C++.
Ken Bloom
+2  A: 

Depending on what behaviour you want, you either can't, or you need to implement the ‘toString()‘ method to get print(ln) to print out a textual representation of your object.

Paul Wagland