Boxing and Widening

前端 未结 7 1671
小蘑菇
小蘑菇 2020-12-30 08:22

What is the difference between these two. I know Boxing is converting primitive values to reference. What is widening. Also what should be the sequence first boxing should b

7条回答
  •  天命终不由人
    2020-12-30 09:17

    • Widening beats boxing eg. go(int) will call go(long) instead of go(Integer) if both are available
    • Widening beats var-args eg go(byte,byte) will call go(int,int) instead of go(byte...x) method.
    • Boxing beats var-args eg go(byte,byte) will call go(Byte,Byte) instead of go(byte...x) method.
    • widening depends on inheritance tree. Eg. go(dog) can call go(Animal)
    • primitive wrapper widening is not possible so go(Short) cannot call go(Integer) since they are not in the same inheritance hierarchy .
    • You CANNOT widen and then box. Eg. go(int) cannot call go(Long) since to call go(Long) the compiler need to convert int to Integer then Integer to Long which is not possible.(rule mentioned above)
    • You can box and then widen. Eg. An int can boxed to Integer and then widen to Object

提交回复
热议问题