12

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.

Community
  • 1
  • 1
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
  • 1
    According to the JLS (http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.9),"It is a compile-time error to attempt to explicitly instantiate an enum type". So, I would guess the static is redundant. – Tetramputechture Oct 21 '14 at 14:11
  • 1
    The JLS referes to something like `new MyEnum()`, not to instantiating inner classes declared inside the enum type. – Tomek Rękawek Oct 21 '14 at 14:30

1 Answers1

10

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.

Tomek Rękawek
  • 9,204
  • 2
  • 27
  • 43