首页 > 解决方案 > Java非静态变量引用错误?

问题描述

    public class Abc {
     int a = 9;
     static void print() {
         System.out.println(a);
    }
}
class AbcTester {
    public static void main(String[] args) {
        Abc test = new Abc();
        test.a = 8;
        test.print();
    }
}

为什么代码会产生“java:无法从静态上下文引用非静态变量 a”错误,即使我已经在 main 方法中创建了该类的实例。我知道静态方法不能使用非静态字段,但是在我创建了类的实例之后,该方法不应该能够使用它吗?

标签: javaclassstatic-methods

解决方案


您不能从静态上下文中引用实例字段。

   public class Abc {
     int a = 9;             // <-- instance field
     static void print() {  // <-- static context (note the static keyword)
         System.out.println(a); // <-- referring to the int field a.
     } 
   }

原因是静态方法在它们的类之间共享。静态方法不需要调用类的显式实例。因此,如果您尝试a从静态上下文访问实例字段(在您的情况下),它不知道class instance要引用哪个。因此它不知道a要访问哪个类的实例字段。


推荐阅读