Why would an Enum implement an Interface?

前端 未结 16 2745
长发绾君心
长发绾君心 2020-11-28 01:34

I just found out that Java allows enums to implement an interface. What would be a good use case for that?

16条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 02:03

    Here's one example (a similar/better one is found in Effective Java 2nd Edition):

    public interface Operator {
        int apply (int a, int b);
    }
    
    public enum SimpleOperators implements Operator {
        PLUS { 
            int apply(int a, int b) { return a + b; }
        },
        MINUS { 
            int apply(int a, int b) { return a - b; }
        };
    }
    
    public enum ComplexOperators implements Operator {
        // can't think of an example right now :-/
    }
    

    Now to get a list of both the Simple + Complex Operators:

    List operators = new ArrayList();
    
    operators.addAll(Arrays.asList(SimpleOperators.values()));
    operators.addAll(Arrays.asList(ComplexOperators.values()));
    

    So here you use an interface to simulate extensible enums (which wouldn't be possible without using an interface).

提交回复
热议问题