为什么不能在循环中隐藏局部变量? [英] Why is it not possible to shadow a local variable in a loop?

查看:32
本文介绍了为什么不能在循环中隐藏局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这种情况,我无法理解阴影.例如下面的代码:

I got this situation I can't understand about shadowing. For example the following code:

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 didn't throw an error when i named
       // the parameter same as the instance variable?
   }
}

推荐答案

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

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

这篇关于为什么不能在循环中隐藏局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆