繁体   English   中英

Java-简短说明

[英]Java - short and casting

我有以下代码片段。

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) { }

以下摘要是否正确(仅针对上面的简短示例)?

  • 不使用类型转换直接初始化只能使用文字或单个变量(只要该值在声明的类型范围内)
  • 如果作业的rhs使用变量处理表达式,则必须进行强制转换

但是,为什么考虑到先前的摘要,我到底需要强制转换第二个方法调用的参数呢?

这些是相关的JLS部分:

JLS 5.1.1身份转换

任何类型都允许从类型到相同类型的转换。

JLS 5.2任务转换

当将表达式的值分配给变量时,将发生赋值转换:必须将表达式的类型转换为变量的类型。 分配上下文允许使用以下之一:

  • 身份转换
  • [...]

另外,如果该表达式是类型为byteshortcharint的常量表达式:

  • 如果变量的类型为byteshortchar ,并且常量表达式的值可以表示为变量的类型,则可以使用缩窄的原始转换。

上述规则解释了以下所有内容:

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。 方法调用转换

特别是方法调用转换不包括作为分配转换一部分的整数常量的隐式缩小。 Java编程语言的设计人员认为,包括这些隐式的缩小转换将为重载的方法匹配解决过程增加额外的复杂性。

我只解释有效的Java 2nd Edition的第41项:明智地使用重载:

确定选择哪个过载的规则非常复杂。 在语言规范中,它们占据了33页,并且几乎没有程序员理解它们的所有精妙之处。


也可以看看

short值进行算术运算的结果始终为int test(7)不起作用,因为您没有说过7是short类型。 这里的编译器应该更聪明。

通话test(7);的“ 7” test(7); 是一个int ,不会自动转换为short

当您声明和初始化short值时,它可以工作,但这是编译器的一种特殊情况。 方法调用不存在这种特殊情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM