What are enums and why are they useful?

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

    What gave me the Ah-Ha moment was this realization: that Enum has a private constructor only accessible via the public enumeration:

    enum RGB {
        RED("Red"), GREEN("Green"), BLUE("Blue");
    
        public static final String PREFIX = "color ";
    
        public String getRGBString() {
            return PREFIX + color;
        }
    
        String color;
    
        RGB(String color) {
            this.color = color;
        }
    }
    
    public class HelloWorld {
        public static void main(String[] args) {
            String c = RGB.RED.getRGBString();
            System.out.print("Hello " + c);
        }
    }
    

提交回复
热议问题