Using nested enum types in Java

前端 未结 4 613
暖寄归人
暖寄归人 2020-12-02 15:29

I have a data structure in mind that involves nested enums, such that I could do something like the following:

Drink.COFFEE.getGroupName();
Drink.COFFEE.COLU         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 16:18

    I was recently curious myself if this could be done somewhat satisfactorily. This is the solution I ended up with, whose API I think also closer matches the tree structure of enums that the asker originally wanted:

    public interface Drink {
    
        String groupName();
        String label();
    
        enum Coffee implements Drink {
    
            COLUMBIAN("Columbian Blend"),
            ETHIOPIAN("Ethiopian Blend");
    
            private final String label;
    
            Coffee(String label) {
                this.label = label;
            }
    
            @Override
            public String groupName() {
                return "Coffee";
            }
    
            @Override
            public String label() {
                return label;
            }
        }
    
        enum Tea implements Drink {
    
            MINT("Mint"),
            HERBAL("Herbal"),
            EARL_GREY("Earl Grey");
    
            private final String label;
    
            Tea(String label) {
                this.label = label;
            }
    
            @Override
            public String groupName() {
                return "Tea";
            }
    
            @Override
            public String label() {
                return label;
            }
        }
    }
    
    public static void main(String[] args) {
        Drink choice = Drink.Tea.EARL_GREY;
    
        System.out.println(choice.groupName());  // Tea
        System.out.println(choice.label());  // Earl Grey
    }
    

提交回复
热议问题