我有以下代码片段。
public static void main(String[] args) {
short a = 4;
short b = 5;
short c = 5 + 4;
short d = a;
short e = a + b; // does not compile (expression treated as int)
short z = 32767;
short z_ = 32768; // does not compile (out of range)
test(a);
test(7); // does not compile (not applicable for arg int)
}
public static void test(short x) { }
以下摘要是否正确(仅针对上面的简短示例)?
但是,为什么考虑到之前的摘要,我到底需要强制转换第二个方法调用的参数呢?
最佳答案
这些是有关JLS的部分:
JLS 5.1.1 Identity Conversion
JLS 5.2 Assignment Conversion
上面的规则解释了以下所有内容:
short a = 4; // representable constant
short b = 5; // representable constant
short c = 5 + 4; // representable constant
short d = a; // identity conversion
short e = a + b; // DOES NOT COMPILE! Result of addition is int
short z = 32767; // representable constant
short z_ = 32768; // DOES NOT COMPILE! Unrepresentable constant
至于为什么不能编译:test(7); // DOES NOT COMPILE! There's no test(int) method!
这是因为只为赋值定义了常量的缩小转换。不用于方法调用,它具有完全不同的规则。JLS 5.3. Method Invocation Conversion
我没有解释方法解析如何精确地工作,而是引用有效的Java 2nd Edition,第41项:明智地使用重载:
也可以看看
short x = 3; x += 4.6;
由于复合赋值的语义而编译关于Java-简短说明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2720738/