我有一个枚举作为
enum OperationsType {
ADD("+"), SUB("-"), DIV("/"), MUL("*");
private String opcodes;
private OperationsType(String opcodes) {
this.opcodes = opcodes;
}
public String toString() {
return this.opcodes;
}
}
这里所有枚举类型都没有任何constant Specific method
所以javac
只为enum
创建一个类文件作为
OperationsType.class
但是如果我在相同代码中为所有枚举类型添加 constant Specific method
,则 javac
会创建 5 个类文件。
Operations.class
Operations$1.class
Operations$2.class
Operations$3.class
Operations$4.class
下面的代码
enum Operations {
ADD("+") {
public double apply(double a, double b) {
return a + b;
}
},
SUB("-") {
public double apply(double a, double b) {
return a - b;
}
},
DIV("/") {
public double apply(double a, double b) {
return a / b;
}
},
MUL("*") {
public double apply(double a, double b) {
return a * b;
}
};
private String opcodes;
private Operations(String opcodes) {
this.opcodes = opcodes;
}
public abstract double apply(double a, double b);
}
所以我怀疑为什么 compiler
为每个 enum type
创建了 4 个不同的类,如果它们有 constant Specific method
但没有创建不同的类,如果它们没有常量特定方法
?
最佳答案
具有常量特定方法的枚举是使用匿名内部类实现的。如 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.
匿名内部类是通过创建名称为 OuterClass$1
、OuterClass$2
等的类文件来实现的,这正是枚举的情况。
关于java - 如果每个枚举类型具有特定于常量的方法,为什么要为它们创建不同的类文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29940746/