Why does Java allow “public static final” in nested classes for simple types and not arrays? [duplicate]

StackOverflow https://stackoverflow.com/questions/9825293

  •  25-05-2021
  •  | 
  •  

Question

Possible Duplicate:
Cannot declare Public static final String s = new String(“123”) inside an inner class

In the following example, why are 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 I need by using public interface GroupOne instead, but I'd still like to understand why the constants are treatly differently. The only difference I see is that the third one is an array and therefore its members are modifiable, but it seems like that would trigger a different error if any.

Was it helpful?

Solution

One point to note is your inner class (GroupOne) depends on the parent class (Constants) as you've defined it as public final class GroupOne. I suspect if you define it as public static final class GroupOne it will work for you.

The compiler error message should tell you this:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top