Can enums be subclassed to add new elements?

前端 未结 15 2068
臣服心动
臣服心动 2020-11-22 12:02

I want to take an existing enum and add more elements to it as follows:

enum A {a,b,c}

enum B extends A {d}

/*B is {a,b,c,d}*/

Is this po

15条回答
  •  佛祖请我去吃肉
    2020-11-22 12:25

    Here is a way how I found how to extend a enum into other enum, is a very straighfoward approach:

    Suposse you have a enum with common constants:

    public interface ICommonInterface {
    
        String getName();
    
    }
    
    
    public enum CommonEnum implements ICommonInterface {
        P_EDITABLE("editable"),
        P_ACTIVE("active"),
        P_ID("id");
    
        private final String name;
    
        EnumCriteriaComun(String name) {
            name= name;
        }
    
        @Override
        public String getName() {
            return this.name;
        }
    }
    

    then you can try to do a manual extends in this way:

    public enum SubEnum implements ICommonInterface {
        P_EDITABLE(CommonEnum.P_EDITABLE ),
        P_ACTIVE(CommonEnum.P_ACTIVE),
        P_ID(CommonEnum.P_ID),
        P_NEW_CONSTANT("new_constant");
    
        private final String name;
    
        EnumCriteriaComun(CommonEnum commonEnum) {
            name= commonEnum.name;
        }
    
        EnumCriteriaComun(String name) {
            name= name;
        }
    
        @Override
        public String getName() {
            return this.name;
        }
    }
    

    of course every time you need to extend a constant you have to modify your SubEnum files.

提交回复
热议问题