Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifier static is only allowed in constant variable declarations

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);     } } 

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" is just more elegant/readable than "key, trigger, keys"

Or maybe I just have Obsessive–compulsive disorder, still I'd like to do it my way.

like image 329
Timotheus Avatar asked Jun 22 '11 12:06

Timotheus


People also ask

Can a variable be declared as a static constant?

There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static.

Why is a modifier static not allowed here?

Because the static keyword is meant for providing memory and executing logic without creating Objects, a class does not have a value logic directly, so the static keyword is not allowed for outer class and mainly as mentioned above static can't be used at Package level. It only used within the Class level.

What is static function in Java?

In Java, a static method is a method that belongs to a class rather than an instance of a class. The method is accessible to every instance of a class, but methods defined in an instance are only able to be accessed by that object of a class.


2 Answers

You can make the Control class static.

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

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).

like image 196
aioobe Avatar answered Sep 28 '22 16:09

aioobe


Make your inner class static and it will work:

private static class Control { ... 
like image 36
Costi Ciudatu Avatar answered Sep 28 '22 15:09

Costi Ciudatu