【发布时间】:2018-12-16 19:41:45
【问题描述】:
以下方法接受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 的默认文字,那么为什么 byte c=15 被接受而不进行强制转换而不是方法参数。
提前谢谢你。
【问题讨论】:
-
它猜测是因为方法重载:您可以有另一个
subtractNumbers方法,其第一个参数为 int,在这种情况下,subtractNumber(15,16,17)将调用第二个。 -
通过执行
(byte) 15和byte c = 15你将这个int值向下转换为byte,所以没有编译错误