Java嵌套范围和变量的名称隐藏

Luc*_*uca 2 c++ java name-hiding

我正在学习使用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 
    }                   
  }

}
Run Code Online (Sandbox Code Playgroud)

从C++的角度来看,这很奇怪,因为我可以嵌套我想要的范围,并且我能够隐藏变量.这是Java的正常行为还是我遗漏了什么?

Jon*_*eet 8

它不是关于"第一个嵌套范围" - 它是Java允许局部变量隐藏字段但不允许它隐藏另一个局部变量的问题.据推测,Java的设计者认为这种隐藏对可读性不利.

请注意,实例初始值设定项中的局部变量示例不会产生错误 - 此代码有效:

class C {
  int a = 11;

  {
    // Local variable hiding a field. No problem.
    double a = 0.2;
  }
}
Run Code Online (Sandbox Code Playgroud)