In a class, I need to define different actions which are passed into a method. Now, all instances can safely share these action, so I thought I could safely make the enum static.
But in almost all examples I've seen, the nested enum is never made static. So, which is the preferred way to define a nested (private) enum? Does it actually make sense to not make it static?
public class MyClass {
private static enum Action {
READ("read"),
WRITE("write");
final String value;
Action(String value) {
this.value = value;
}
String getValue() {
return value;
}
}
// attributes, methods, constructors and so on
}
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).
All Enums are implicitly static, its just you don't need to write the static keyword.
Enum FieldsThe enum constructor must be private . You cannot use public or protected constructors for a Java enum . If you do not specify an access modifier the enum constructor it will be implicitly private .
Yes, enums are effectively static.
The Java Language Specification, section 8.9, states:
Nested enum types are implicitly static. It is permissable to explicitly declare a nested enum type to be static.
So you can, but you don't have to, and it'll make no difference. Personally I don't think I'd bother, as it's implicit anyway.
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