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?
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With