我正在做有关Java类的练习。代码如下。
如果在嵌入式调用资源管理器之前添加静态修饰符,则可以运行代码而不会出现问题。但是,如果我不添加“静态”,则会看到以下错误:
内部类Government中的非法静态声明。Explorer修饰符“ static”仅在常量变量声明中允许。
顺便说一句,该练习来自加州大学伯克利分校的CS61B 2018年春季。提供了原始代码here:
public class Government {
private int treasury = 5;
public static Government greaterTreasury(Government a, Government b) {
if (a.treasury > b.treasury) {
return a;
}
return b;
}
public static class Explorer {
public static void doStuff(Government a, Government b) {
Government favorite = Government.greaterTreasury(a, b);
System.out.println("The best government has treasury " + favorite.treasury);
}
}
public static void main(String[] args){
Government a = new Government();
a.treasury = 10;
Government b = new Government();
b.treasury = 11;
Government.Explorer.doStuff(a, b);
}
}
答案 0 :(得分:0)
没有外部类的实例,就不能引用非静态内部类。
内部类不能具有静态成员(常量除外)
请参见Why can't we have static method in a (non-static) inner class?