从静态方法访问非静态变量计数?

时间:2015-08-14 10:18:18

标签: java

如何从静态main方法访问非静态变量计数。我期待一个错误。编译器应该抛出错误。如果我错了,请纠正我 无法从静态上下文访问非静态成员

class sync {

  private int count;
  public static void main (String args[]) {

    sync obj =new sync();
    obj.do();
  }

  public void do() {

    Thread t =new Thread(new Runnable () {

      public void run() {
        for(int i=0;i<=1000;i++) {
          count++;
        }
      }
    });

    Thread t1=new Thread (new Runnable () {

      public void run () {
        for(int i=0;i<=1000;i++) {
          count++;
        }
      }
    });

    t.start();
    t1.start();
    System.out.println(count) ;
  }
}

1 个答案:

答案 0 :(得分:3)

在静态方法中没有访问它。

在访问它的地方,它不是在静态上下文中访问,而是通过同步实例访问。

public static void main(String[] a){
  int a = count; // this would be wrong, and cause the error you expect
}

public static void main(String[] a){
  sync a = new sync();
  int b = a.getCount(); // or even a.count; for a public variable
  // is valid, since even though it is within a static method, it is not in 
  // a static context
}