我知道变量范围由块 {的开头和块的结尾} 包围。如果在块中声明了相同的变量,则会发生编译错误已定义的变量。但请看下面的示例。
I know that variable scope is enclosed by a start of block { and an end of block }. If the same variable is declared within the block, then the compile error Variable already defined occurs. But take a look at following example.
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 无法重新声明。
Here, x can be redeclared in a method, although it's already declared in the class. But in the if block, x can't be redeclared.
为什么重新声明类范围变量不会产生错误,但方法范围变量重新声明会产生错误?
Why is it that redeclaration of a class scope variable doesn't generate an error, but a method scope variable redeclaration generates an error?
推荐答案这是因为 int x = 0 不是变量而是实例字段。允许局部变量与字段具有相同的名称。为区分变量和具有相同名称的字段,我们使用此前缀作为实例字段或类名称用于类字段。例如。
This is because int x=0 is not a variable but an instance field. Local variables are allowed to have the same names as fields. To distinguish between a variable and a field with the same name we use this prefix for instance fields or class name for class fields. E.g.
int x = this.x更多推荐
类范围变量与方法范围变量
发布评论