"non-static variable cannot be initialized from a static context" Java 错误



我正在研究如何制作一个接受任何对象的参数,我找到了答案,我尝试重新创建代码。 但问题是每当我初始化 Bee、Horse 和 Apple 时,它总是显示错误"非静态变量无法从静态上下文初始化"。 那么这是怎么错的呢?

public class Testing{
public static void main(String[]args){
Bee a= new Bee();
Horse b= new Horse();
Apple c= new Apple():
}
private interface holder{
public int getX();
}
private class Bee implements holder{
int a=52;
public int getX(){
return a;
}
}
private class Horse implements holder{
int a=62;
public int getX(){
return a;
}
}

只需将BeeHorse的类定义从:

private class Bee implements Holder {...}

自:

private static class Bee implements Holder {...}

如果没有static关键字,该类将被视为内部类,并且需要实例化封闭类的实例。例如,如果没有static你必须写:

Testing testing = new Testing();
Bee bee = testing.new Bee();

这没有意义,因为TestingBee并没有真正的关系。因此,使用static可以像您尝试的那样完成:

Bee bee = new Bee(); // works

相关内容

最新更新