switch语句中的最终变量大小写
问题内容:
final int a = 1;
final int b;
b = 2;
final int x = 0;
switch (x) {
case a:break; // ok
case b:break; // compiler error: Constant expression required
}
/* COMPILER RESULT:
constant expression required
case b:break;
^
1 error
*/
为什么会出现这种错误?如果我愿意final int b = 2
,一切都会正常。
问题答案:
b
可能尚未初始化,可以分配多个值。在您的示例中,它显然已初始化,但是编译器可能不知道(而且也不知道)。想像:
final int b;
if (something) {
b = 1;
} else {
b = 2;
}
编译器需要中的常量switch
,但的值b
取决于某些外部变量。