Java非静态变量引用错误?

问题描述 投票:0回答:1
    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();
    }
}

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

java class static-methods
1个回答
0
投票

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

   public class Abc {
     int a = 9;             // <-- instance field
     static void print() {  // <-- static context (note the static keyword)
         System.out.println(a);
    }
© www.soinside.com 2019 - 2024. All rights reserved.