关于java中变量范围和阴影的问题 [英] question about variable scope and shadowing in java

查看:108
本文介绍了关于java中变量范围和阴影的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这种情况我无法理解阴影。例如,以下代码

I got this situation i cant 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 didnt 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.

这些参数名称不能重新声明为方法的局部变量,也不能作为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.)

这篇关于关于java中变量范围和阴影的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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