Java 中的作用域规则
有人可以帮助我理解 Java 中的作用域规则吗?这显然是无效的:
{
int i = 0;
System.out.println(i); // fine, of course
}
System.out.println(i); // syntax error
i
是在 {}
内声明的,并且在外部不可用。那么这个呢:
for (int i = 0; i < 10; i++) {
System.out.println(i); // fine, of course
}
System.out.println(i); // syntax error, same as above.
我对这里的语法错误感到惊讶。 i
在外部作用域中声明,但稍后不可用。它是否通过 for 循环的某些特殊规则绑定到内部块作用域?还有其他情况可能会发生这种情况吗?
Can someone help me understand the scoping rules in Java? This is clearly not valid:
{
int i = 0;
System.out.println(i); // fine, of course
}
System.out.println(i); // syntax error
i
is declared within the {}
, and it's not available outside. So what about this:
for (int i = 0; i < 10; i++) {
System.out.println(i); // fine, of course
}
System.out.println(i); // syntax error, same as above.
I'm surprised at the syntax error here. i
is declared in the outer scope yet it is not available later on. Is it bound to the inner block scope by some special rule for for
loops? Are there other scenarios where this can happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
想想 for 循环实际上是这样表示的:
think of for loop actually represented like this:
是的,情况确实如此。
显然有局部变量声明:
另请参阅:
来自语言规范。
Yes, this is exactly the case.
There's obviously the local variable declaration:
See also:
From the language specification.
这是 Java 中
for
循环的定义行为。来源: http://download.oracle.com/javase/tutorial/java /nutsandbolts/for.html
It's the defined behavior of the
for
loop in Java.Source: http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html