不能。静态方法属于类、随类加载即存在,而非静态成员属于对象、仅在实例化后才存在;静态方法无this引用,无法确定操作哪个对象的成员,故编译报错“cannot reference from static context”。
静态方法中不能直接调用非静态成员(包括字段和方法),因为非静态成员属于实例,而静态方法不依赖于任何对象实例。想“在静态方法中使用非静态成员”,本质是需要先获得一个有效的对象实例。
Java 中 static 修饰的成员属于类本身,随类加载而存在;而非 static 成员属于具体对象,只有创建对象后才存在。静态方法运行时可能还没有任何实例,JVM 无法确定该访问哪个对象的非静态成员,因此编译器直接报错:「non-static variable/method cannot be referenced from a static context」。
只要先创建或获取一个对象实例,就能通过该实例访问其非静态成员。常见方式有:
错误写法:
立即学习“Java免费学习笔记(深入)”;
class Example {正确写法(三种常见修复):
new Example().print();
public static void main(String[] args) { new Example().run(); } void run() { print(); } 或者 static void main(String[] args) { Example e = new Example(); e.print(); }
private static final Example INSTANCE = new Example();,然后在静态方法中调用 INSTANCE.print();
频繁出现“静态方法要调用非静态成员”,往往说明设计存在问题: