【发布时间】:2015-02-09 08:09:45
【问题描述】:
考虑以下代码sn-p:
class TypeCast{
public static void main(String[] args){
byte by = 4; //compiler casts int literal to byte
doCasting(4); //Compilation Error: external type casting is required. WHY ?
}
public static void doCasting(byte by){
}
}
我认为上面的代码 sn-p 是不言自明的。当 int 文字赋值给 byte 类型时,编译器会自动执行所需的转换。当我们使用 int 字面量调用采用 byte 参数的方法时,同样的事情不会发生。为什么?
【问题讨论】:
-
你不能。基本数字常量被视为整数,因此您必须将其显式向下转换为字节才能将其作为参数传递。据我所知,没有捷径。 Source