开发者

Why object declared after one case label is available in others? [duplicate]

开发者 https://www.devze.com 2023-03-06 12:52 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Variable scope in a switch case
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Variable scope in a switch case

开发者_如何学C

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消