块范围变量 [英] Block scope variables

查看:184
本文介绍了块范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这将编译

class X
{  
    public static void main(String args[])
    {
        {
            int a = 2;
        }
        {
            int a = 3;
        }       
    }
}

p>

This won't

class X
{  
    public static void main(String args[])
    {

        int a = 2;

        {
            int a = 3;
        }       
    }
}

也许是C的工作原理?)。这是什么原因,因为不可能在外部块中的一个块中声明一个变量?

I expected both to compile (maybe it is the way C works?). What is the reason because it is not possible to declare a variable in a block with the same name of one in the outer block?

推荐答案

p>简短的答案是:因为这是Java语言在 JLS§6.4

The short answer is: Because this is the way the Java language is defined in JLS §6.4.

您可能会使用其他语言,这就是所谓的变量阴影。然而,Java语言的发明者认为这是一个他们不想用他们的语言的尴尬的功能:

You might be used from other languages that this so called variable shadowing is allowed. However, the inventors of the Java languages thought this was an awkward feature that they did not want in their language:


这个限制有助于检测

This restriction helps to detect some otherwise very obscure bugs.

但是,你在Java的其他地方发现了阴影,因为作者在JLS的同一部分: / p>

However, you find shadowing elsewhere in Java as the authors state in the same section of the JLS:


局部变量对成员进行遮蔽的类似限制是
认为不切实际,因为在超类中添加了一个成员
可能导致子类必须重命名局部变量。相关的
注意事项限制嵌套类的
成员对局部变量的影子,或者局部
在嵌套类中声明的局部变量的影子。

A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well.

这意味着在实践中,以下代码是合法的:

This means in practice that the following code is legal:

class A {
   int x = 0;
   void m() {
     int x = 10; // Shadows this.x
   }
}

允许通过声明一个具有相同名称的方法局部变量来隐藏一个实例变量,因为有人可能在某一天你不能再扩展 A 的功能如果阴影是非法的,则编译一个类 B

As the authors describe, it is allowed to shadow an instance variable by declaring a method local variable with the same name because of the possibility of someone extending the functionality of A at one day where you could not longer compile a class B if shadowing was illegal:

class B extends A {
   void m() {
     int x = 10; // Shadows A.this.x if A declares x
   }
}

如果你考虑像C这样的语言,允许阴影,你可以找到这样的尴尬代码:

If you consider a language like C, where shadowing is allowed, you can find awkward code like this:

int x;
int main() 
{
  {
    int x = 0;
    {
      extern int x;
      x = 1;
    }
    printf("%d\n", x); // prints 0
  }
  printf("%d\n", x); // prints 1
  return 0;
}

这个程序不是那么容易遵循,因此可能不会产生结果预期,感谢可变阴影。

This program is not so easy to follow and might therefore not produce the results you expect, thanks to variable shadowing.

这篇关于块范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆