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条回答
Ridiculous、
2楼-- · 2019-01-28 01:50

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-28 01:51

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.

查看更多
一夜七次
4楼-- · 2019-01-28 01:57

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.

查看更多
戒情不戒烟
5楼-- · 2019-01-28 01:57

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.

查看更多
Emotional °昔
6楼-- · 2019-01-28 01:57

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.

查看更多
Anthone
7楼-- · 2019-01-28 02:00

Local variable shadowing is prohibited in Java on purpose (see this answer).
The idea is that this helps decreasing bugs.

查看更多
登录 后发表回答