Why object declared after one case label is available in others? [duplicate]
开发者_如何学CPossible Duplicate:
Variable scope in a switch case
I've got a code like this:
switch(a) {
case b:
Object o = new Object();
return o;
case c:
o = new Object();
return o;
}
and i'm interesting why it's possible to use variable declared after first case label in the second one even if first state will never be reached?
Despite being in different cases, the variables local to the switch
statement are in the same block, which means they are in the same scope.
As far as I know, new scope in Java is only created in a new block of code. A block of code (with more than one line) has to be surrounded by curly braces. The code in the cases of a switch statement is not surrounded by curly braces, so it is part of the whole statement's scope.
However, you can actually introduce a new scope to the statement by adding curly braces:
switch (cond) {
case 1:{
Object o = new Object();
}
break;
case 2:{
// Object o is not defined here!
}
break;
}
精彩评论