SCJP: can't widen and then box, but you can box and then widen

前端 未结 5 742
余生分开走
余生分开走 2020-12-17 03:05

I\'m studying for the SCJP exam and I ran into an issue I can\'t really wrap my head around.

The book says you can\'t widen and then box, but you can box and then wi

5条回答
  •  庸人自扰
    2020-12-17 03:33

    It isn't a widening because Byte doesn't fit in a Long. That's why it doesn't works.

    You can box into a Byte and then widen into an Object or a Number.

    As your book says :

    we're back to trying to widen a Byte to a Long


    In your case, I suppose the code looks like this :

    byte b = 1;
    Long l = b;
    

    b is changed into a Byte (boxing first) but can't be changed into a Long because Byte isn't a subclass of Long.

    In more steps :

    byte b = 1;
    Byte byteB = b; //works
    Long l = byteB; //doesn't work
    

提交回复
热议问题