隐式类型转换不适用于方法参数?
Implicit type cast not working for method parameters?
考虑以下代码片段:
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){
}
}
我认为上面的代码片段是不言自明的。当 int
文字分配给 byte
类型时,编译器会自动执行所需的转换。当我们调用带有 byte
参数和 int 文字的方法时,不会发生同样的事情。为什么?
这是转换的分配上下文 (JLS 5.2) and an invocation context (JLS 5.3) 之间的区别。
分配上下文转换包括:
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
- A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
调用上下文转换中不存在。
除了可能简化重载解析之外,我不清楚为什么要这样设计语言 - 如果您有:
doCasting(5);
...
doCasting(int x) {}
doCasting(byte b) {}
那么你可以争论它们中的任何一个是“最佳匹配” - byte
是比 int
更具体的类型,但如果你认为文字是 int
,那么 byte
重载需要转换,而 int
重载不需要。
通过使 byte
重载完全不适用,问题被删除。
考虑以下代码片段:
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){
}
}
我认为上面的代码片段是不言自明的。当 int
文字分配给 byte
类型时,编译器会自动执行所需的转换。当我们调用带有 byte
参数和 int 文字的方法时,不会发生同样的事情。为什么?
这是转换的分配上下文 (JLS 5.2) and an invocation context (JLS 5.3) 之间的区别。
分配上下文转换包括:
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
- A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
调用上下文转换中不存在。
除了可能简化重载解析之外,我不清楚为什么要这样设计语言 - 如果您有:
doCasting(5);
...
doCasting(int x) {}
doCasting(byte b) {}
那么你可以争论它们中的任何一个是“最佳匹配” - byte
是比 int
更具体的类型,但如果你认为文字是 int
,那么 byte
重载需要转换,而 int
重载不需要。
通过使 byte
重载完全不适用,问题被删除。