What are enums and why are they useful?

后端 未结 27 2147
一整个雨季
一整个雨季 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:30

    enum means enumeration i.e. mention (a number of things) one by one.

    An enum is a data type that contains fixed set of constants.

    OR

    An enum is just like a class, with a fixed set of instances known at compile time.

    For example:

    public class EnumExample {
        interface SeasonInt {
            String seasonDuration();
        }
    
        private enum Season implements SeasonInt {
            // except the enum constants remaining code looks same as class
            // enum constants are implicitly public static final we have used all caps to specify them like Constants in Java
            WINTER(88, "DEC - FEB"), SPRING(92, "MAR - JUN"), SUMMER(91, "JUN - AUG"), FALL(90, "SEP - NOV");
    
            private int days;
            private String months;
    
            Season(int days, String months) { // note: constructor is by default private 
                this.days = days;
                this.months = months;
            }
    
            @Override
            public String seasonDuration() {
                return this+" -> "+this.days + "days,   " + this.months+" months";
            }
    
        }
        public static void main(String[] args) {
            System.out.println(Season.SPRING.seasonDuration());
            for (Season season : Season.values()){
                System.out.println(season.seasonDuration());
            }
    
        }
    }
    

    Advantages of enum:

    • enum improves type safety at compile-time checking to avoid errors at run-time.
    • enum can be easily used in switch
    • enum can be traversed
    • enum can have fields, constructors and methods
    • enum may implement many interfaces but cannot extend any class because it internally extends Enum class

    for more

提交回复
热议问题