我知道变量作用域被块{
的开始和块}
的结尾包围。如果在块内声明了相同的变量,则会发生编译错误Variable already defined
。但看看下面的例子。类范围变量vs方法范围变量
public class Test{
int x=0;// Class scope variable
public void m(){
int x=9; //redeclaration of x is valid within the scope of same x.
if(true){
int x=7; // but this redeclaration generates a compile time error.
}
}
这里,x
可以在方法中重新声明,尽管它在类中声明。但在if
区块中,x
无法重新声明。
为什么重新声明类作用域变量不会产生错误,但方法作用域变量重新声明会产生错误?
是的,它只是碰巧,这是允许的。字段和变量是内存中具有相同标识符的不同空间。海事组织不应该被允许,没有人应该这样做。 – Radiodef