问题描述
class MyClass {
void myMethod(byte b) {
System.out.print("myMethod1");
}
public static void main(String [] args) {
MyClass me = new MyClass();
me.myMethod(12);
}
}
我知道 myMethod()
的参数是 int
文字,而参数 b
的类型是byte,则此代码将生成编译时错误.(可以通过对参数 myMethod((byte)12)
使用显式字节强制转换来避免这种情况)
I understand that the argument of myMethod()
being an int
literal, and the parameter b
being of type byte, this code would generate a compile time error. (which could be avoided by using an explicit byte cast for the argument: myMethod((byte)12)
)
class MyClass{
byte myMethod() {
return 12;
}
public static void main(String [ ] args) {
MyClass me = new MyClass();
me.myMethod();
}
}
遇到这种情况后,考虑到12是 int
文字和 myMethod()
的返回类型,我希望上面的代码也会产生编译时错误.是字节.但是不会发生此类错误.(不需要显式的强制转换: return(byte)12;
)
After experiencing this, I expected that the above code too would generate a compile time error, considering that 12 is an int
literal and the return type of myMethod()
is byte. But no such error occurs. (No explicit cast is needed: return (byte)12;
)
谢谢.
推荐答案
在这种情况下,Java支持缩小.从 Java语言规范任务转换:
Java supports narrowing in this case. From the Java Language Spec on Assignment Conversion:
这篇关于为什么这里不需要显式强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!