Java enum with multiple value types

后端 未结 1 1780
有刺的猬
有刺的猬 2020-12-23 09:12

Basically what I\'ve done is write an enum for States, and I want to not only be able to access them just as states but also access their abbreviation and whether or not the

相关标签:
1条回答
  • 2020-12-23 09:31

    First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

    Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

    Here's how you should do it with all the suggestions above:

    public enum States {
        ...
        MASSACHUSETTS("Massachusetts",  "MA",   true),
        MICHIGAN     ("Michigan",       "MI",   false),
        ...; // all 50 of those
    
        private final String full;
        private final String abbr;
        private final boolean originalColony;
    
        private States(String full, String abbr, boolean originalColony) {
            this.full = full;
            this.abbr = abbr;
            this.originalColony = originalColony;
        }
    
        public String getFullName() {
            return full;
        }
    
        public String getAbbreviatedName() {
            return abbr;
        }
    
        public boolean isOriginalColony(){
            return originalColony;
        }
    }
    
    0 讨论(0)
提交回复
热议问题