修饰符 static 只允许在常量变量声明中 [英] Modifier static is only allowed in constant variable declarations
问题描述
我有一个内部类,用于存储我用于游戏的控件的信息,现在我想在其中存储一个静态 ArrayList,其中包含所有控件的名称.但是我收到了这个错误:Modifier static 只允许在常量变量声明中"
I have an inner class that stores the info of the controls I'm using for a game, now I want to store a static ArrayList in it that holds all the names of the controls. But I am getting this error: "Modifier static is only allowed in constant variable declarations"
private class Control{
public static ArrayList<String> keys = new ArrayList<String>();
public final String key;
public final Trigger trigger;
Control(String k, Trigger t){
key = k;
trigger = t;
keys.add(key);
}
}
现在我知道这可以通过从类中取出 ArrayList 并将其存储在主类中来轻松解决.但我更愿意将所有信息保存在一个班级中,以便我可以访问所有内容.
Now I know this can easily be solved by taking the ArrayList out of the class and storing it in the main class. But I'd prefer to keep all the information in one class where I can access everything.
Control.key、Control.trigger、Control.keys"只是比键、触发器、键"
也许我只是有强迫症,但我还是想按照自己的方式去做.
Or maybe I just have Obsessive–compulsive disorder, still I'd like to do it my way.
推荐答案
您可以将 Control
类设为静态.
You can make the Control
class static.
private static class Control {
^^^^^^
// Ok to have static members:
public static ArrayList<String> keys = new ArrayList<String>();
...
<小时>
Java 语言规范第 8.1.3 节中对此进行了描述
8.1.3 内部类和封闭实例
内部类是未显式或隐式声明为静态的嵌套类.内部类不得声明静态初始值设定项(第 8.7 节)或成员接口.内部类不得声明静态成员,除非它们是编译时常量字段(第 15.28 节).
8.1.3 Inner Classes and Enclosing Instances
An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).
这篇关于修饰符 static 只允许在常量变量声明中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!