为什么 Java 中的 Switch 语句可以包含 FINAL 变量作为 CASE? ##
在我检查过的 JDK7 中,无法将值重新分配给 final 变量,如下所示。但是,为什么最终变量“x”可以包含在 case 的 Switch 语句中,即使最终变量“x”的值不能重新分配?
尽管 Oracle 定义 Java 编译器将 final 变量作为初始化值而不是变量名,但为什么可以这样做? http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4
请告诉我这是 Java 编译器的技术错误还是检查 Switch 语句中最终变量大小写的异常或特殊用途?
class Example{
public static void main(String args[]){
final int x=100;
//x=200; //error: cannot assign a value to final variable x
//The below piece of code compiles
switch(x){
case 200: System.out.println("200");
case 300: System.out.println("300");
}
}
}
最佳答案
这种情况呢?
public class Foo
{
private final int x;
public Foo(int x){this.x = x;}
public void boo()
{
switch(x)
{
case 200: System.out.println("200");
case 300: System.out.println("300");
}
}
}
或者这个:
public static void doSomething(final int x)
{
switch(x)
{
case 200: System.out.println("200");
case 300: System.out.println("300");
}
}
关于java - 为什么 Java 中的 Switch 语句可以包含 FINAL 变量作为 CASE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15053290/