Widening and Boxing Java primitives.
I know it is not possible to widen a wrapper class from one to another as they are not from the same inheritence tree. Why though is it not possible to widen a primitive to another primitive type and autobox the widened primitive?
Given that a byte argument can be passed to a method that expects an int, why cant the byte in the following example be widened to an int and then boxed to an Integer?
class ScjpTest{
static void goInteger(Integer x){
System.out.println("Going with an Integer");
}
static void goInt(int x){
System.out.println("Going with an int");
}
public static void main(String args[]){
byte b = 5;
goInt(b);
goInteger(b);
}
}
In the above example, goInt(b)
is accepted by the compiler but goInteger(b)
is rejected.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…