javac++name-hiding

Java nested scopes and variables' name hiding


I'm learning name look up in Java, and coming from C++ I found interesting that even if Java lets me nest however many blocks of code,I am allowed to hide a name only in the first nested scope:

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

}

this is weird from a C++ perspective,since there I can nest how many scopes I want,AND I'm able to hide variables as I like. Is this the normal behaviour of Java or am I missing something?


Solution

  • It's not about the "first nested scope" - it's a matter of Java allowing a local variable to hide a field, but not allowing it to hide another local variable. Presumably the designers of Java believed such hiding to be bad for readability.

    Note that your example of a local variable in an instance initializer does not create an error - this code is valid:

    class C {
      int a = 11;
    
      {
        // Local variable hiding a field. No problem.
        double a = 0.2;
      }
    }