Why different class files are created for each enum type if they have constant-specific method?

前端 未结 2 413
既然无缘
既然无缘 2021-01-21 06:42

i have one enum as

enum OperationsType {
  ADD(\"+\"), SUB(\"-\"), DIV(\"/\"), MUL(\"*\");

  private String opcodes;

  private OperationsType(String opcodes)          


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 07:13

    Enums with constant-specific methods are implemented using anonymous inner classes. As mentioned in The Java Language Specification:

    The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors.

    Anonymous inner classes are implemented by creating class files with names like OuterClass$1, OuterClass$2 etc., and this is exactly what happens in the case of the enum.

提交回复
热议问题