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

前端 未结 5 738
余生分开走
余生分开走 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:34

    the language is confusing.

    Basically you can't go in this fashion:
    byte -> Byte -> Long
    because Byte and Long don't share an is-a relationship.
    So, it tries to do this:
    byte -> long -> Long
    But it can't do that either(apparently due to compiler limitations). So, it fails and throws an error.

    But, on the other hand you CAN do this:
    byte -> Byte -> Object
    because Byte is-an Object.

    consider 2 functions and a byte variable:

    toLong(Long x)
    toObject(Object x)
    byte b = 5;

    Then this statement will be illegal:
    toLong(b);
    // because b -> new Byte(b) -> new Long(new Byte(b)) is illegal.
    AND byte -> long -> Long can't be done due to compiler limitations.

    but this statement is legal:
    toObject(b);
    // because b -> new Byte(b) -> new Object(new Byte(b)) is legal.

提交回复
热议问题