Is this really widening vs autoboxing?

后端 未结 3 1099
醉梦人生
醉梦人生 2021-01-07 16:41

I saw this in an answer to another question, in reference to shortcomings of the Java spec:

There are more shortcomings and this is a subtle topic. Check

3条回答
  •  没有蜡笔的小新
    2021-01-07 17:10

    Yes it is, try it out in a test. You will see "long" printed. It is widening because Java will choose to widen the int into a long before it chooses to autobox it to an Integer, so the hello(long) method is chosen to be called.

    Edit: the original post being referenced.

    Further Edit: The reason the second option would print Integer is because there is no "widening" into a larger primitive as an option, so it MUST box it up, thus Integer is the only option. Furthermore, java will only autobox to the original type, so it would give a compiler error if you leave the hello(Long) and removed hello(Integer).

提交回复
热议问题