local scope in Java

前端 未结 8 2006
轮回少年
轮回少年 2020-12-20 23:31

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#).<

相关标签:
8条回答
  • 2020-12-21 00:01

    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.

    0 讨论(0)
  • 2020-12-21 00:02

    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.

    0 讨论(0)
  • 2020-12-21 00:03

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

    0 讨论(0)
  • 2020-12-21 00:05

    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.

    0 讨论(0)
  • 2020-12-21 00:09

    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.

    0 讨论(0)
  • 2020-12-21 00:10

    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.

    0 讨论(0)
提交回复
热议问题