Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are inner classes in enums always static in Java?

Tags:

java

enums

pmd

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.

like image 648
Wim Deblauwe Avatar asked Oct 21 '14 14:10

Wim Deblauwe


People also ask

Are enum static by default?

Yes, enums are effectively static.

Can enum be an inner class in Java?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Are enum classes static?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Is enum always static?

As enums are inherently static , there is no need and makes no difference when using static-keyword in enums . If an enum is a member of a class, it is implicitly static.


1 Answers

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.

like image 137
Tomek Rękawek Avatar answered Oct 30 '22 13:10

Tomek Rękawek