2

我正在学习 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的正常行为还是我错过了什么?

4

2 回答 2

9

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

请注意,您在实例初始化程序中的局部变量示例不会产生错误 - 此代码有效:

class C {
  int a = 11;

  {
    // Local variable hiding a field. No problem.
    double a = 0.2;
  }
}
于 2015-09-28T09:25:12.647 回答
3

我不是 C++ 人,但从 C++ 方面来看确实很奇怪,如果我是设计师,我会完全消除这种行为。这确实会导致错误并且难以阅读代码。

为了在 Java 中过上平静的生活,这种行为被完全消除了。如果您像现在看到的那样尝试这样做,编译器会向您显示一个错误。

于 2015-09-28T09:26:20.057 回答