Can I set enum start value in Java?

前端 未结 9 1679
长情又很酷
长情又很酷 2020-11-30 18:09

I use the enum to make a few constants:

enum ids {OPEN, CLOSE};

the OPEN value is zero, but I want it as 100. Is it possible?

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 19:00

    Java enums are not like C or C++ enums, which are really just labels for integers.

    Java enums are implemented more like classes - and they can even have multiple attributes.

    public enum Ids {
        OPEN(100), CLOSE(200);
    
        private final int id;
        Ids(int id) { this.id = id; }
        public int getValue() { return id; }
    }
    

    The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.

    See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.

提交回复
热议问题