块作用域变量 [英] Block scope variables

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

问题描述

这将编译

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

这不会

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?

推荐答案

简短的回答是:因为这是 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.

但是,正如作者在 JLS 的同一部分中所述,您会发现 Java 中的其他地方存在阴影:

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
", x); // prints 0
  }
  printf("%d
", 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天全站免登陆