我知道变量范围包含在 block {
的开头和 block }
的结尾。如果在 block 内声明了相同的变量,则会发生编译错误 Variable already defined
。但是请看下面的示例。
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
block 中,x
不能重新声明。
为什么类作用域变量的重新声明不会产生错误,而方法作用域变量的重新声明会产生错误?
最佳答案
这是因为int x=0
不是变量而是实例字段。允许局部变量与字段同名。为了区分变量和同名字段,我们对实例字段使用 this
前缀,对类字段使用类名。例如。
int x = this.x
关于java - 类范围变量与方法范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19473301/