local scope in Java
Why开发者_Go百科 is it that curly braces do not define a separate local scope in Java? I was expecting this to be a feature common to the main curly brace languages (C, C++, Java, C#).
class LocalScopeTester
{
public static void main(String... args)
{
Dog mine = new Dog("fido");
if (mine.getName().equals("ace"))
{
Dog mine = new Dog("spot"); // error: duplicate local
}
else
{
Dog mine = new Dog("barkley"); // error: duplicate local
{
Dog mine = new Dog("boy"); // error: duplicate local
}
}
}
}
They do define a separate local scope, but you still cannot mask local variables from a parent scope (but you can of course mask instance variables).
But you can define new variables (with different names) and their scope will be limited to within the braces.
Local variable shadowing is prohibited in Java on purpose (see this answer).
The idea is that this helps decreasing bugs.
The braces do scope the variable but anything inside a brace can also 'see' further up the brace. In all the cases you have, mine
is already defined as fido.
To put it more succinctly. The children are scoped to their parents as well but not vice versa.
They do define a separate local scope, just it is an error if a local variable hides another.
Try defining a variable (with a unique name) inside a block, then accessing from outside that block to see that it is indeed scoped to the block, and only that block.
Blocks define a local scope, but don't allow you to redefine a variable with the same name as another variable in an outer local scope. If it did, there would be no way to access the "hidden" variable.
It does define a local scope... the variables declared inside curly braces have the braces' scope. However what you are trying to do is redeclare an already existing variable. In my opinion, it's not Java that's wrong in this case, but C++ for letting you do it (I assume that's what you were comparing it to). Nonetheless, even if the language would allow it, why would you do it? Poor readability right there, and possible cause for bugs.
Run this and you'll get an error that the variable is already declared as int i=5
and one cannot redefine. So, the Parent never takes what its child got.
So, what if the Parent sacrifices and removes his declaration of int i=5
?
public class Ouch {
public static void main(String[] args) {
int i=5;
for(int i=0;i<5;i++);
for(int i=0;i<5;i++);
}
}
Now, the Parent sacrificed its declaration and both the children enjoy and the code runs successfully.
public class Ouch {
public static void main(String[] args) {
//int i=5;
for(int i=0;i<5;i++);
for(int i=0;i<5;i++);
}
}
It's forgotten in Java but I think Java is wrong because in ALL "block structured" languages it is authorized to do this (not only in C++ but also in Pascal, ADA, C, and so on...) and sometime we want to hide a variable of the enclosing block.
精彩评论