Is it possible to assign numeric value to an enum in Java?

后端 未结 6 1002
傲寒
傲寒 2020-12-07 17:29

Is anything like this possible in Java? Can one assign custom numeric values to enum elements in Java?

public enum EXIT_CODE {
    A=104, B=203;
}

6条回答
  •  一向
    一向 (楼主)
    2020-12-07 17:39

    If you're looking for a way to group constants in a class, you can use a static inner class:

    public class OuterClass {
        public void exit(boolean isTrue){
            if(isTrue){
                System.exit(ExitCode.A);
            }else{
                System.exit(ExitCode.B);
            }
        }
        public static class ExitCode{
            public static final int A = 203;
            public static final int B = 204;
        }   
    }
    

提交回复
热议问题