Can I make an abstract enum in Java?

后端 未结 3 1797
花落未央
花落未央 2020-12-30 19:09

Below is a valid enum declaration.

public enum SomeEnumClass {

    ONE(1), TWO(2), THREE(3);

    private int someInt;

    public SomeEnumClass(int someInt         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-30 19:41

    If you really need to "extend an enum", you could use the the pre-Java 1.5 Typesafe Enum Pattern (see the bottom of http://www.javacamp.org/designPattern/enum.html ) which actually uses a class, not an enum. You lose the ability to use the EnumSet with your "enum"s and you lose some auto-generated methods such as items(), but you get the ability to override methods.

    An example:

    // Typesafe enum pattern
    public static abstract class Operator {
        public static final Operator ADD = new Operator("+") {
            @Override
            public Double apply(Double firstParam, Double secondParam) {
                return firstParam + secondParam;
            }
        };
        public static final Operator SUB = new Operator("-") {
            @Override
            public Double apply(Double firstParam, Double secondParam) {
                return firstParam - secondParam;
            }
        };
        public static final Operator MUL = new Operator("*") {
            @Override
            public Double apply(Double firstParam, Double secondParam) {
                return firstParam * secondParam;
            }
        };
        public static final Operator DIV = new Operator("/") {
            @Override
            public Double apply(Double firstParam, Double secondParam) {
                return firstParam / secondParam;
            }
        };
    
        private static final Operator[] _ALL_VALUES = {ADD, SUB, MUL, DIV};
        private static final List ALL_VALUES = Collections.unmodifiableList(Arrays.asList(_ALL_VALUES));
    
        private final String operation;
    
        private Operator(String c) {
            operation = c;
        }
    
        // Factory method pattern
        public static Operator fromToken(String operation) {
            for (Operator o : Operator.items())
                if (o.operation.equals(operation))
                    return o;
            return null;
        }
    
        public Iterable items() {
            return ALL_VALUES;
        }
    
        public abstract Double apply(Double firstParam, Double secondParam); 
    
    }
    

提交回复
热议问题