关于java中变量范围和阴影的问题

blo*_*sky 4 java variables scope shadowing

我得到了这种情况我无法理解阴影.例如以下代码

class Foo {
   int a = 5;
   void goFoo(int a) { 
       // No problem naming parameter as same as instance variable
       for (int a = 0; a < 5; a++) { }
       //Now the compiler complains about the variable a on the for loop
       // i thought that the loop block had its own scope so i could shadow
       // the parameter, why the compiler didnt throw an error when i named
       // the parameter same as the instance variable?
   }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你耐心等待.

Jon*_*eet 12

您可以将局部变量阴影设置为实例/静态变量 - 但是您不能使一个局部变量(您的循环计数器)影响另一个局部变量或参数(您的参数).

从Java语言规范,第14.4.3节:

如果声明为局部变量的名称已经声明为字段名称,那么该外部声明将在局部变量的整个范围内被遮蔽(第6.3.1节).

注意"字段名称"部分 - 它指定它必须是被遮蔽的字段.

第8.4.1节开始:

方法(第8.4.1节)或构造函数(第8.8.1节)的参数范围是方法或构造函数的整个主体.

这些参数名称不能重新声明为方法的局部变量,也不能重新声明为方法或构造函数的try语句中的catch子句的异常参数.

(它继续讨论本地类和匿名类,但它们在你的情况下是无关紧要的.)