Java 修饰符 static 只允许在常量变量声明中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6440010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Modifier static is only allowed in constant variable declarations
提问by Timotheus
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"
我有一个内部类,用于存储我用于游戏的控件的信息,现在我想在其中存储一个静态 ArrayList,其中包含控件的所有名称。但我收到此错误:“修改器静态只允许在常量变量声明中”
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);
}
}
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.
现在我知道这可以通过从类中取出 ArrayList 并将其存储在主类中来轻松解决。但我更愿意将所有信息保存在一个可以访问所有内容的类中。
"Control.key, Control.trigger, Control.keys"is just more elegant/readable than "key, trigger, keys"
“Control.key,Control.trigger,Control.keys”比“key,trigger,keys”更优雅/可读
Or maybe I just have Obsessive–compulsive disorder, still I'd like to do it my way.
或者也许我只是有强迫症,但我仍然想按照我的方式去做。
采纳答案by aioobe
You can make the Control
class static.
您可以将Control
类设为静态。
private static class Control {
^^^^^^
// Ok to have static members:
public static ArrayList<String> keys = new ArrayList<String>();
...
This is described in the Java Language Specification Section §8.1.3
这在 Java 语言规范部分 §8.1.3 中有描述
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).
8.1.3 内部类和封闭实例
内部类是未显式或隐式声明为静态的嵌套类。内部类不得声明静态初始值设定项(第 8.7 节)或成员接口。内部类不能声明静态成员,除非它们是编译时常量字段(第 15.28 节)。
回答by Costi Ciudatu
Make your inner class static and it will work:
使您的内部类静态,它将起作用:
private static class Control { ...