Enums: methods exclusive to each one of the instances

前端 未结 3 1011
有刺的猬
有刺的猬 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:26

    You cannot refer to those methods, because you are effectively creating anonymous (*) class for each enum. As it is anonymous, you can reference such methods only from inside your anonymous class itself or through reflection.

    This technique is mostly useful when you declare abstract method in your enumeration, and implement that method for each enum individually.

    (*) JLS 8.9 Enums part says: "The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type."

提交回复
热议问题