Instantiate enum class

后端 未结 9 1528
南笙
南笙 2020-12-03 05:34

Consider I am having the following enum class,

public enum Sample {
    READ,
    WRITE
}

and in the following class I am trying to test th

9条回答
  •  星月不相逢
    2020-12-03 05:58

    You cannot instantiate an Enum, thats the whole point of having an Enum. For example you would use enum when defining properties of some thing which would never change like:

    enum TrafficLight {
         RED("stop"),
         YELLOW("look"),
         GREEN("go")
    }
    

    private string value;

    private TrafficLight(String value) {
        this.value = value;
    }
    
    public getValue() {
        return value;
    }
    

    Now if you want to get the value of the enum, you can use valueOf method of enums. The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though;

    TrafficLight trafficLight = TrafficLight.valueOf("RED")
    String value = trafficLight.getValue();
    

    If you do TrafficLight.valueOf("XYZ"), it will throw an IllegalArgumentException

提交回复
热议问题