Java 非静态变量引用错误?
Java non-static variable reference error?
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 方法中创建了 class 的实例,但为什么代码会产生 "java: non-static variable a cannot be referenced from a static context" 错误。我知道静态方法不能使用非静态字段,但是在我创建了 class 的实例之后,该方法不应该能够在它上面工作吗?
您不能从静态上下文中引用实例字段。
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.
}
}
原因是静态方法在 classes 之间共享。静态方法不需要调用 class 的显式实例。因此,如果您尝试从静态上下文访问实例字段(在您的情况下为 a
),它不知道要引用哪个 class instance
。因此它不知道要访问 a
的哪个 class 的实例字段。
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 方法中创建了 class 的实例,但为什么代码会产生 "java: non-static variable a cannot be referenced from a static context" 错误。我知道静态方法不能使用非静态字段,但是在我创建了 class 的实例之后,该方法不应该能够在它上面工作吗?
您不能从静态上下文中引用实例字段。
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.
}
}
原因是静态方法在 classes 之间共享。静态方法不需要调用 class 的显式实例。因此,如果您尝试从静态上下文访问实例字段(在您的情况下为 a
),它不知道要引用哪个 class instance
。因此它不知道要访问 a
的哪个 class 的实例字段。