Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make this private enum static or not?

Tags:

java

enums

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
}
like image 861
helpermethod Avatar asked Sep 14 '11 14:09

helpermethod


People also ask

Can we make enum 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).

Are all enums static?

All Enums are implicitly static, its just you don't need to write the static keyword.

Can I make enum private?

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 .

Are enums static by default?

Yes, enums are effectively static.


1 Answers

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.

like image 87
Jon Skeet Avatar answered Oct 03 '22 01:10

Jon Skeet