2

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?

Luca
  • 1,658
  • 4
  • 20
  • 41

2 Answers2

9

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;
  }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Nice to get an answer from you... `:)` – Praveen Kumar Purushothaman Sep 28 '15 at 09:28
  • Correct answer !! Classic case of someone trying to use a language before reading through the first chapter :-) – Geek Sep 28 '15 at 09:30
  • yes,thanks for the clarification about nesting.. I noticed that even if I declare a new name into a local scope ( initializer block,method or loop ) that doesn't hide a field I cannot hide that name,the compiler complains – Luca Sep 28 '15 at 09:32
  • 1
    @Geek the anwer is correct indeed and you're just guessing wrong since I've been studying C++ and Java for 6 months now, but I guess you learn everything on page one of your manual,good for you! – Luca Sep 28 '15 at 09:34
  • @Luca: Yes, exactly - you can't hide one local variable with another. – Jon Skeet Sep 28 '15 at 09:36
  • @Luca : No offense intended. Happy Learning !! – Geek Sep 28 '15 at 09:41
3

I'm not a C++ guy but that really looks weird from C++ side and If I were the designer , I completely remove that behaviour. That really causes bugs and hard to read the code.

To lead a peaceful life in Java that behaviour is completely removed. Compiler shows you an error if you try to do that as you are seeing it now.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307