How to implement boxing and unboxing in my own class?

一笑奈何 提交于 2020-01-11 09:26:34

问题


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?


回答1:


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.




回答2:


autoBoxing or unboxing is available only with primitive in java like Long wrapper class for long

Integer for int

but user defiend not possible,

best you can do constructor initialize like

Myclass m=new Myclass(100);



回答3:


It's not possible to implement automatic boxing and unboxing for your own class - auto(un)boxing is a language feature, implemented in the Java compiler.



来源:https://stackoverflow.com/questions/15919475/how-to-implement-boxing-and-unboxing-in-my-own-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!