Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement boxing and unboxing in my own class?

Tags:

java

boxing

In Java there is no operator overriding like i C++ so I can't figure out how to implement a boxing/unboxing for my own class.

For example it's possibile to use boxing and unboxing with Integer or Float when we do somethings like this:

int myVar = new Integer(25);

But how can I implement something similar in my class MyObject? (in the case I want to wrap a primitive type myself). Is there any code example?

like image 440
user1883212 Avatar asked Apr 10 '13 07:04

user1883212


1 Answers

There is no way to implement auto-boxing and auto-unboxing for a user-defined class.

You can of course provide named methods to do the job. However, you would have to call them explicitly every time you need to box or unbox something.

like image 187
NPE Avatar answered Sep 19 '22 00:09

NPE