Wim Deblauwe
Wim Deblauwe

Reputation: 26868

Are inner classes in enums always static in Java?

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

For example (In the real code, there are some methods declared on the enum 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 would it be a PMD bug?

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

Upvotes: 12

Views: 5801

Answers (1)

Tomek Rękawek
Tomek Rękawek

Reputation: 9304

static keyword is not redundant. You may create a static nested class (with the static keyword) or an inner class (without it). In the first case the class won't be assigned to any particular enum value. In the second case, instances of the inner class need to have an enclosing 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 example above you can't create an instance of the MyInnerClass directly from the MyEnum:

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

In order to do this, you need to have a static nested class, but then you can't use something like MyEnum.this.

Upvotes: 10

Related Questions