Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use of static enum?

Tags:

java

enums

I was trying to find the difference between declaring an enum static?

public class Example {
  public static enum Days {
    MONDAY(1);

    private int day;
    private Days(int day) {
      this.day = day;
    } 

    public int getDayNum() {
      return day;
    }
  }
}

And the one below

public class Example {
  public enum Days {
    MONDAY(1);

    private int day;
    private Days(int day) {
      this.day = day;
    } 

    public int getDayNum() {
      return day;
    }
  }
}

I can access both of the above the exact same way

Example.Days.MONDAY.getDayNum();

This is because an enum is static, final. So whats the difference? When to use either of the above?

like image 581
noMAD Avatar asked Dec 02 '22 22:12

noMAD


1 Answers

As per the JLS 8.9:

Nested enum types are implicitly static. It is permissible to explicitly declare a nested enum type to be static.

This implies that it is impossible to define a local (§14.3) enum, or to define an enum in an inner class (§8.1.3).

like image 160
AllTooSir Avatar answered Dec 19 '22 23:12

AllTooSir