Java 变量的作用域

标签 java scope

我不明白为什么这段代码的输出是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不再活了??所以第一个xx=10在类中声明A ?如果有的话怎么办x上课A ?它会打印 11

最佳答案

局部变量只能从声明它们的方法中访问。考虑到这一点,可以重写代码以避免 shadowing the member variables以及由此产生的困惑:

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 表示法进行访问;但我建议不要隐藏变量 - 选择有意义的名称。)

关于Java 变量的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24732644/

相关文章:

java - 单例或具有静态字段的类

python - 使用函数返回的变量时出现名称错误

actionscript-3 - 冲突范围 : Global Functions and Class Methods of the Same Name

python 作用域 - 子作用域应该有权访问父作用域?

java - 在 libgdx 上暂停游戏时暂停计时器中的任务

Java 正则表达式能够单独处理嵌套匹配

java - 为 hadoop MapReduce Cleanup 添加进度跟踪机制

logging - 在包之间共享库时的集中日志记录配置

java - Spring Caching - 如何管理不同范围的缓存?

java - 获取jsp中存储在session中的对象的属性