Java Enums can have behavior?

前端 未结 7 1395
清酒与你
清酒与你 2021-02-02 16:56

In Java, an Enum can do the great things that Enums do, but can also have methods (behavior and logic). What advantage does that have over using a class using an enum? Simple ex

7条回答
  •  臣服心动
    2021-02-02 17:07

    Take a look at java/joda time classes, where enums do hell of a lot of job.

    Here is an example of java.time.Month:

    public enum Month implements TemporalAccessor, TemporalAdjuster {
        JANUARY,
        FEBRUARY,
        MARCH,
        APRIL,
        MAY,
        JUNE,
        JULY,
        AUGUST,
        SEPTEMBER,
        OCTOBER,
        NOVEMBER,
        DECEMBER;
    
        private static final Month[] ENUMS = Month.values();
    
        public static Month of(int month) {
            if (month < 1 || month > 12) {
                throw new DateTimeException("Invalid value for MonthOfYear: " + month);
            }
            return ENUMS[month - 1];
        }
    
        // About a dozen of other useful methods go here 
    
    }
    

提交回复
热议问题