Why does Java allow "public static final" in nested classes for simple types and not arrays?

Possible duplicate:
Cannot declare public static final String s = new String ("123") inside inner class

In the following example, why is CONST_ONE, CONST_TWO allowed, but CONST_THREE is flagged with the error "inner classes cannot have static declarations"?

package com.myco.mypack;

public final class Constants {

    public final class GroupOne {
        public static final String CONST_ONE = "stuff";
        public static final int CONST_TWO = 2;
        public static final int[] CONST_THREE = new int[]{3};

    public static final int[] CONST_FOUR = new int[]{4};


I can get the behavior public interface GroupOne

I want by using instead, but I would still like to understand why constants are related differently. The only difference I can see is that the third one is an array and therefore its members are mutable, but it looks like this will lead to another error, if any.


source to share

1 answer

It should be noted that your inner class (GroupOne) depends on the parent class (constants) since you defined it as public final class GroupOne

. I suspect that if you define it as public static final class GroupOne

, it will work for you.

The compiler error message should tell you the following:

the field CONST_THREE cannot be declared static; static fields can only be declared in static or top level types


In your case, GroupOne is neither static nor top-level. It works for interfaces as they cannot be directly instantiated



All Articles