首先,请注意本文是在讨论编译时常量表达式。只有编译时常量表达式才允许窄化转换。从语言规范,第 5.2 节:
此外,如果表达式是 byte、short、char 或 int 类型的常量表达式(第 15.28 节):
- 如果变量的类型是 byte、short 或 char,并且常量表达式的值可以用变量的类型表示,则可以使用窄化原语转换。
由于没有文字值,因此存在从编译时常量short到的隐式缩小赋值转换这一事实并不是很明显;只有和。要获得编译时间常数,您必须使用以下技巧之一:byteshortintlongshort
// Casting:
byte b2 = (short) 42;
// Compile-time constant short value:
static final short s = 42;
byte b = s;
另一方面,您的讲义还说从longtoint和更小的整数类型存在隐式缩小转换。这是不正确的,只能在表达式类型为byte、short、char或时使用转换int。他们用来说明的代码片段会产生编译时错误:
int i = 0x12345678L; /* "error: possible loss of precision" */