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


i have 1 enum

enum operationstype {   add("+"), sub("-"), div("/"), mul("*");    private string opcodes;    private operationstype(string opcodes) {     this.opcodes = opcodes;   }    public string tostring() {     return this.opcodes;   } } 

here enum type doesn't have constant specific method javac creating 1 class file enum

operationstype.class 

but if add constant specific method in same code enum type javac creating 5 class files.

operations.class operations$1.class operations$2.class operations$3.class operations$4.class 

for below code

enum operations { add("+") {     public double apply(double a, double b) {         return + b;     } }, sub("-") {     public double apply(double a, double b) {         return - b;     } }, div("/") {     public double apply(double a, double b) {         return / b;     } }, mul("*") {     public double apply(double a, double b) {         return * b;     } };  private string opcodes;  private operations(string opcodes) {     this.opcodes = opcodes; }  public abstract double apply(double a, double b); } 

so have doubt why compiler has created 4 different classes each enum type if having constant specific method not creating different classes if don't have constant specific method?

enums constant-specific methods implemented using anonymous inner classes. mentioned in the java language specification:

the optional class body of enum constant implicitly defines anonymous class declaration (§15.9.5) extends enclosing enum type. class body governed usual rules of anonymous classes; in particular cannot contain constructors.

anonymous inner classes implemented creating class files names outerclass$1, outerclass$2 etc., , happens in case of enum.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -