且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不能在循环中隐藏局部变量?

更新时间:2022-04-13 03:28:53

你可以让一个局部变量隐藏一个实例/静态变量 - 但你不能让一个局部变量(你的循环计数器)隐藏另一个局部变量或参数(你的参数).

You can make a local variable shadow an instance/static variable - but you can't make one local variable (your loop counter) shadow another local variable or parameter (your parameter).

来自 Java 语言规范,第 14.4 节.3:

From the Java Language Specification, section 14.4.3:

如果声明为局部变量的名称已声明为字段名称,则该外部声明将在整个局部变量范围内隐藏(第 6.3.1 节).

If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed (§6.3.1) throughout the scope of the local variable.

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

Note the "field name" part - it's specifying that it has to be a field that is shadowed.

来自 第 8.4.1 节一个>:

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

The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.

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

These parameter names may not be redeclared as local variables of the method, or as exception parameters of catch clauses in a try statement of the method or constructor.

(继续讨论本地类和匿名类,但它们与您的情况无关.)

(It goes on to talk about local classes and anonymous classes, but they're irrelevant in your case.)