java - 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 方法中创建了该类的实例。我知道静态方法不能使用非静态字段,但是在我创建了类的实例之后,该方法不应该能够使用它吗?
解决方案
您不能从静态上下文中引用实例字段。
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
要访问哪个类的实例字段。
推荐阅读
- java - 如果找不到 ID,则在 for 循环中仅打印一次
- xml - Windows 10 在加载展台模式应用程序时出错,代码为 0x80073CF9
- python - 是否可以在 FTP 服务器上调用 xarray open_mfdataset?
- pdf - 使用 PDFBox 将 PDF 转换为图像会产生奇怪的字符(字体问题)
- mysql - 将值拆分为多行
- android - 是否可以将 EditTextPreference 限制为数字?
- html - 使照片变暗超出文字
- python - Tensorboard 图 ReduceLROnPlateau
- javascript - Storybook docs-addon 模块解析失败:意外的令牌
- python - 我无法让 pyqt5 在 anaconda python 下运行