DJ *_*han 5 java variables final case switch-statement
为什么Java中的Switch语句可以包含一个FINAL变量作为CASE?##
在我检查的JDK7中,无法将值重新分配给最终变量,如下所示.但是,为什么最终变量"x"可以包含在一个案例事件的Switch语句中,而最终变量"x"的值是否无法重新分配?
为什么这样做可以尽管Oracle定义Java编译器将最终变量作为初始化值而不是变量名称?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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这种情况怎么办?
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者也许是这个:
public static void doSomething(final int x)
{
switch(x)
{
case 200: System.out.println("200");
case 300: System.out.println("300");
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,您可以final在函数中传递参数:
//the function doesn't know what x value is,
//but it knows that it can't modify its value
public someFunction(final int x) {
x += 1; //compiler error
switch(x) {
case 200: System.out.println("200");
break;
case 300: System.out.println("300");
break;
}
}
//the function doesn't know what x value is,
//but it knows that it can modify it
//for internal usage
public someOtherFunction(int x) {
switch(x) {
case 200:
x += 200;
break;
case 300:
x += 300;
break;
}
System.out.println(x);
}
Run Code Online (Sandbox Code Playgroud)