修改静态只允许在不断的变量声明 [英] Modifier static is only allowed in constant variable declarations
问题描述
我有一个存储我使用一个游戏控制的信息的内部类,现在我要存储在一个静态的ArrayList保存控件的所有名称。但我得到这个错误:修改静态只允许在不断的变量声明
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 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中出类并将其存储在主类来解决。但是我preFER保持在一个类中的所有信息,在这里我可以访问一切。
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.
推荐答案
您可以让控制
类的静态。
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).
这篇关于修改静态只允许在不断的变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!