2011-06-22 81 views
18

我有一个内部类,它存储了我用于游戏的控件的信息,现在我想在其中存储一个静态ArrayList,它包含控件的所有名称。但我收到此错误:“修改静态只允许在不断的变量声明”修饰符static只允许在常量变量声明中

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中出类并将其存储在主类来解决。但我更愿意将所有信息保存在一个可以访问所有内容的课程中。

“Control.key,Control.trigger,Control.keys” 只比 “键,触发键”

或者,也许我只是有强迫症更优雅/可读,我仍想按照自己的方式去做。

+0

给你如何创建内更多信息类? – fmucar

回答

30

您可以使Control类为静态。

private static class Control { 
     ^^^^^^ 

    // Ok to have static members: 
    public static ArrayList<String> keys = new ArrayList<String>(); 

    ... 

这在Java语言规范Section §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

描述让你的内部类的静态和它的工作:

private static class Control { ...