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.
Yes, enums are effectively static.
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
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).
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With