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

问题描述

这将编译

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语言在。

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:

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

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

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

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.

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

07-24 14:37