What are enums and why are they useful?

后端 未结 27 1287
一整个雨季
一整个雨季 2020-11-22 07:06

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits

27条回答
  •  隐瞒了意图╮
    2020-11-22 07:39

    It is useful to know that enums are just like the other classes with Constant fields and a private constructor.

    For example,

    public enum Weekday
    {
      MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    } 
    

    The compiler compiles it as follows;

    class Weekday extends Enum
    {
      public static final Weekday MONDAY  = new Weekday( "MONDAY",   0 );
      public static final Weekday TUESDAY = new Weekday( "TUESDAY ", 1 );
      public static final Weekday WEDNESDAY= new Weekday( "WEDNESDAY", 2 );
      public static final Weekday THURSDAY= new Weekday( "THURSDAY", 3 );
      public static final Weekday FRIDAY= new Weekday( "FRIDAY", 4 );
      public static final Weekday SATURDAY= new Weekday( "SATURDAY", 5 );
      public static final Weekday SUNDAY= new Weekday( "SUNDAY", 6 );
    
      private Weekday( String s, int i )
      {
        super( s, i );
      }
    
      // other methods...
    }
    

提交回复
热议问题