Are inner classes in enums always static in Java?

I have an enum class that contains an inner class in Java.

For example (In real code, there are some methods declared in the listing that internally use the inner class):

public enum MyEnum{ VALUE_1, VALUE_2; private static class MyInnerClass // is static here needed or can it be removed? { } } 

PMD tells me that the "static" modifier is not needed (violation of the UnusedModifier rule). Is this correct or is it a PMD error?

Note: This question is not a duplicate, it is the opposite of what I ask here.

+7
java enums pmd
source share
1 answer

static keyword is not redundant. You can create a static nested class (with the static ) or an inner class (without it). In the first case, the class will not be tied to any specific enumeration value. In the second case, instances of the inner class must have a private instance - one of the enum values:

 public class Test { public static void main(String[] args) { MyEnum.VALUE_1.createInnerObject().showName(); MyEnum.VALUE_2.createInnerObject().showName(); } public enum MyEnum { VALUE_1, VALUE_2; public MyInnerClass createInnerObject() { return new MyInnerClass(); } private class MyInnerClass { public void showName() { System.out.println("Inner class assigned to " + MyEnum.this + " instance"); } } } } 

In the above example, you cannot create an instance of MyInnerClass directly from MyEnum :

 new MyEnum.MyInnerClass(); // this will fail 

To do this, you need to have a static nested class, but then you cannot use something like MyEnum.this .

+6
source share

All Articles