且构网

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

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

更新时间:2022-12-18 15:50:45

你可以使局部变量阴影成为一个实例/静态变量 - 但你不能让一个局部变量(你的循环计数器)影响另一个局部变量变量或参数(您的参数)。

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.

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

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.)