变量的 Java 范围 [英] Java scope of a variable

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

问题描述

我不明白为什么这段代码的输出是10:

I do not understand why the output of this code is 10:

package uno;

public class A
{
    int x = 10;
    A(){int x = 12; new B();}
    public static void main(String args[]){
        int x = 11;
        new A();
    }
    class B{
        B(){System.out.println(x);}
    }
}

这个例子中的范围是如何工作的?为什么 System.out.println(x); 打印 10?是不是因为指令 System.out.println(x); 在辅助函数的括号之外:A(){int x=12;new B();}int x = 12 只存在于那里,但是当 System.out.println(x); 被调用时,x = 12 没有生命了??那么第一个 x 是在 A 类中声明的 x=10 吗?如果A 类中有任何x 会怎样?它会打印 11 吗?

How does the scope in this example work? Why System.out.println(x); prints 10? Is it because the instruction System.out.println(x); is outside the parentesis of the costructor: A(){int x=12; new B();} and so int x = 12 lives only there but when System.out.println(x); is invoked, x = 12 lives no longer?? So the first x is x=10 declared in class A? What if there were any x in class A? Would it print 11?

推荐答案

局部变量只能从它们声明的方法中访问.考虑到这一点,可以重写代码以避免 隐藏成员变量以及由此产生的混乱:

Local variables can only be accessed from within the method they are declared. With this in mind, the code can be rewritten to avoid shadowing the member variables and the resulting confusion:

package uno;
public class A{
  // And instance member variable (aka field)
  int field_A_x = 10;
  A(){
    // A local variable, only visible from within this method
    int constructor_x = 12;
    new B(); // -> prints 10
    // Assign a new value to field (not local variable), and try again
    field_A_x = 12;
    new B(); // -> prints 12
  }
  public static void main(String args[]){
    // A local variable, only visible from within this method
    int main_x = 11;
    new A();
  }
  class B{
    B(){
      // The inner class has access to the member variables from
      // the parent class; but the field not related to any local variable!
      System.out.println(field_A_x);
    }
  }
}

(阴影成员变量总是可以用 this.x 表示法访问;但我建议不要隐藏变量 - 选择有意义的名称.)

(Shadowed member variables can always be accessed in the this.x notation; but I would suggest not shadowing variables - choose meaningful names.)

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

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