如何解决非静态方法不能从静态上下文中引用?
问题描述:
class Base {
Base show() {
System.out.println("Base");
return new Base();
}
class Child4 extends Base {
Child4 show() {
System.out.println("Child4");
return new Child4();
}
}
public static void main(String... s) {
Child4 C1 = new Child4();
C1.show();
}
}
答
在您的示例中,Child4
是Base
类的非静态内部类(有关内部类的文档,请参阅here)。这意味着您需要类Base
的实例才能实例化类Child4
的对象。
由于在你的例子中没有从Child4
实例到外部Base
实例的访问,所以看起来并不打算使用非静态内部类。你应该声明这个内部类静态的,
static class Child4 extends Base {
这样,调用new Child4
将从main
静态上下文合法的。
嗨迪莎。欢迎来到堆栈溢出。请让您更容易理解您的问题:您如何使用您发布的代码进行尝试?你是否收到错误信息,或者代码的行为与你认为的不同?你认为它应该做什么,你观察到了什么行为? –
不要将Child4类嵌套到基类中。使用2个不同的文件:每个类别一个。 –
[非静态变量不能从静态上下文中引用]的可能重复(http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – csmckelvey