local scope in Java

2019-01-28 01:38发布

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

标签: java scope
8条回答
倾城 Initia
2楼-- · 2019-01-28 02:03

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.

查看更多
做个烂人
3楼-- · 2019-01-28 02:05

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++);
    } 
}
查看更多
登录 后发表回答