我正在研究如何制作一个接受任何对象的参数,我找到了答案,我尝试重新创建代码。 但问题是每当我初始化 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;
}
}
只需将Bee
和Horse
的类定义从:
private class Bee implements Holder {...}
自:
private static class Bee implements Holder {...}
如果没有static
关键字,该类将被视为内部类,并且需要实例化封闭类的实例。例如,如果没有static
你必须写:
Testing testing = new Testing();
Bee bee = testing.new Bee();
这没有意义,因为Testing
和Bee
并没有真正的关系。因此,使用static
可以像您尝试的那样完成:
Bee bee = new Bee(); // works