繁体   English   中英

Java变量范围

[英]Java scope of a variable

我不明白为什么这段代码的输出是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);System.out.println(x); 在构造函数的括号之外: A(){int x=12; new B();} A(){int x=12; new B();} ,因此int x = 12仅在其中存在,但在System.out.println(x);时才存在System.out.println(x); 被调用时, x = 12不再存在? 因此,第一个x是在类A声明的x=10 如果A类中有xA怎么办? 它会打印11吗?

局部变量只能从声明它们的方法中访问。 考虑到这一点,可以重写代码以避免隐藏成员变量并避免造成混淆:

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

int x = 10;

这具有实例范围 ,类A的任何成员都可以“看到”此内容。 B类看到了这一点。

int x=12;

这在您的A构造函数中具有局部作用域。 仅在A的构造函数中可见。

int x = 11; 

这次,在您的main方法内部也具有局部作用域。

谁做System.out.println(x); B的构造函数。B看到了什么? int x = 10; 这就是为什么...

此外,,

public class A{
  int x = 10;
  A(){int x=12; new B(); System.out.println(x); //prints 12}
  public static void main(String args[]){
    int x = 11;
    System.out.println(x); // prints 11
    new A();
  }
  class B{
    B(){System.out.println(x); //prints 10, as in your example}
  }
}

尝试如果在第四行中省略int会发生什么:

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

然后输出将为12,因为您没有初始化新的int x

您的内部类看不到您在A类的构造函数中定义的局部变量。 这就是为什么x对于B为10的原因。

编辑:忍者

如果您期望输出为x=12 ,则只需更改

A(){int x=12; new B();}  // remove int here

A(){x=12; new B();} 

它当前正在创建local variable ,因为它是在方法内部声明的。

删除构造函数中的新声明,将更改instance variable的值。

所以输出将是x=12

发生的事情是可变阴影。 检查http://en.wikipedia.org/wiki/Variable_shadowing

如果在本地方法中声明并初始化了具有相同名称的变量,则该值仅在定义该方法的方法中使用。它不会更改全局变量变量。 因此,设置int x = 11int x = 12不会更改x的全局值。 但是,在一种方法中,如果未定义变量,则使用全局值,因此在B类中将打印x的全局值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM