Instantiate enum class

后端 未结 9 1505
南笙
南笙 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 06:10

    I'm answering to the first question. You can easily do it like this:

    public static void main(String[] args) {
    
        Sample.READ.testEnumSample();
    }
    
    public enum Sample {
        READ,
        WRITE;
    
        public void testEnumSample() {
            System.out.println(this);
        }
    }
    
    0 讨论(0)
  • 2020-12-03 06:17

    You cannot create a new enum instance. Otherwise it won't be an enum. You can reference an already existing enum. As in your example

     Sample sample = Sample.READ;
    
    0 讨论(0)
  • 2020-12-03 06:21

    Enums doesn't support public constructors and hence, cannot be instantiated. Enums are for when you have a fixed set of related constants. Exactly one instance will be created for each enum constant.

    0 讨论(0)
提交回复
热议问题