以下方法接受三个类型为 byte,int,int
的参数,并且该方法是从另一个方法调用的,该方法给出了一个编译错误,即方法参数不适用于 int,int ,int
。默认情况下,字节参数只有在显式转换完成后才能识别。
public double subtractNumbers(byte arg1,int arg2,int arg3) {
double sum=arg1+arg2+arg3;
return sum;
}
现在方法调用另一个方法如下
public void call(){
subtractNumbers(15,16,17); /*Compile error,but 15 is in byte acceptable
range of -128 to 127 */
}
如果我将上面的调用更改为 subtractNumbers((byte)15,16,17);
它工作正常
当我将变量声明为 byte c=15
时,它被接受但是当 15 被传递给字节参数时为什么会出现编译错误;
int 是 byte,short,int,long 的默认字面值,这就是为什么字节 c=15 被接受而无需强制转换但不接受方法参数的原因。
提前致谢。
最佳答案
您的问题归结为:
为什么将 15
分配给 byte
在变量声明中有效:
byte b = 15;
但不是在调用方法时?
subtractNumbers(15,16,17);
这是因为这两种情况处于两种不同的上下文。第一个在赋值上下文中,而第二个在调用上下文中。
根据JLS §5.2 Assignment Contexts ,
Assignment contexts allow the use of one of the following:
...
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.
15
当然是一个常量表达式,因此允许从 int
到 byte
的缩小原始转换。
然而,在调用上下文中,这是不正确的:
Strict invocation contexts allow the use of one of the following:
- an identity conversion (§5.1.1)
- a widening primitive conversion (§5.1.2)
- a widening reference conversion (§5.1.5)
Loose invocation contexts allow a more permissive set of conversions, because they are only used for a particular invocation if no applicable declaration can be found using strict invocation contexts. Loose invocation contexts allow the use of one of the following:
- an identity conversion (§5.1.1)
- a widening primitive conversion (§5.1.2)
- a widening reference conversion (§5.1.5)
- a boxing conversion (§5.1.7) optionally followed by widening reference conversion
- an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion
没有提到“narrowing primitive conversion”,所以在调用上下文中是不允许的。
关于java - 将方法参数传递给java中byte,int,int类型的方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240176/