Why 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.
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 ofint i=5
?Now, the Parent sacrificed its declaration and both the children enjoy and the code runs successfully.