【发布时间】:2017-11-19 09:59:23
【问题描述】:
在Java中,为什么局部范围变量不能隐藏,而全局变量可以? 例如:
public class Hello {
static int x = 10;
public static void foo() {
int x = 20; // Hides the global variable with the value of "20" within the
method foo.
}
}
但这是不可能的:
public class Hello {
public static void foo() {
int x = 20;
int y = 1;
if(x >= 20) {
int y = 10; // Cannot hide this
}
}
我知道我不能在更内部的本地范围内隐藏具有本地范围的变量,但问题是为什么会发生这种情况?是因为 Java 的设计方式吗?还有其他类似的例外吗?
【问题讨论】: