我正在学习 Java 中的名称查找,并且来自 C++,我发现有趣的是,即使 Java 允许我嵌套许多代码块,我也只能在第一个嵌套范围内隐藏名称:
// name hiding-shadowing: local variables hide names in class scope
class C {
int a=11;
{
double a=0.2;
//{
// int a; // error: a is already declared in instance initializer
//}
}
void hide(short a) { // local variable a,hides instance variable
byte s;
for (int s=0;;); // error: s in block scope redeclares a
{
long a=100L; // error: a is already declared in (method) local scope
String s; //error: s is alredy defined in (method) local scope
}
}
}
从 C++ 的角度来看,这很奇怪,因为在那里我可以嵌套多少个我想要的范围,并且我可以随意隐藏变量。这是Java的正常行为还是我错过了什么?