Why would an Enum implement an Interface?

前端 未结 16 2751
长发绾君心
长发绾君心 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:52

    Since Enums can implement interfaces they can be used for strict enforcing of the singleton pattern. Trying to make a standard class a singleton allows...

    • for the possibility of using reflection techniques to expose private methods as public
    • for inheriting from your singleton and overriding your singleton's methods with something else

    Enums as singletons help to prevent these security issues. This might have been one of the contributing reasons to let Enums act as classes and implement interfaces. Just a guess.

    See https://stackoverflow.com/questions/427902/java-enum-singleton and Singleton class in java for more discussion.

提交回复
热议问题