Why would an Enum implement an Interface?

前端 未结 16 2750
长发绾君心
长发绾君心 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 01:53

    The Comparable example given by several people here is wrong, since Enum already implements that. You can't even override it.

    A better example is having an interface that defines, let's say, a data type. You can have an enum to implement the simple types, and have normal classes to implement complicated types:

    interface DataType {
      // methods here
    }
    
    enum SimpleDataType implements DataType {
      INTEGER, STRING;
    
      // implement methods
    }
    
    class IdentifierDataType implements DataType {
      // implement interface and maybe add more specific methods
    }
    

提交回复
热议问题