Enums: methods exclusive to each one of the instances

前端 未结 3 1035
有刺的猬
有刺的猬 2020-12-18 19:01

From another question I have learnt that it is possible in Java to define specific methods for each one of the instances of an Enum:

public          


        
3条回答
  •  渐次进展
    2020-12-18 19:16

    Each enum is an anonymous inner class. So like any anonymous inner class, you can add all of the methods you want, but there is no way to reference them outside of the class, as the class doesn't have a type that defines the methods.

    The advantage of allowing methods on the enum implementation is that it allows for a strategy pattern, where the enum itself has an abstract method or a default implementation, and specific members of the enum have implementations of that method that may do something different.

    I have used this technique to greatly reduce code complexity on switch statements. Instead of switching on the enum in some other class, just get a reference to it and call a method, and let the enum itself take care of it. Of course that depends on the scenario if it makes sense, but it can reduce code complexity tremendously.

提交回复
热议问题