gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:09:18 25 4
gpt4 key购买 nike

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

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?
}
}

最佳答案

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

来自 Java 语言规范,section 14.4.3 :

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.

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

来自section 8.4.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.

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.

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

关于java - 为什么不能在循环中隐藏局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4623334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com