public enum Operations {
SINGLE,
MULTIPLE;
private Type operation;
public void setOperation(Type operation) {
this.operation = operation;
}
public Type getOperation() {
return operation;
}
public static void main(String[] args) {
Operations oper1 = Operations.SINGLE;
oper1.setOperation(Type.GET);
Operations oper2 = Operations.SINGLE;
oper2.setOperation(Type.POST);
System.out.println(oper1.getOperation());
System.out.println(oper2.getOperation());
}
}
enum Type {
POST,
GET;
}
在上面的代码中,两个操作的操作值都发生了变化。我怎样才能拥有两个具有不同操作类型的 Operations.SINGLE 实例?
是的,实例是隐式的 static
和 final
。这意味着代码是不明智的。想象一下,两个线程都调用 SINGLE.setOperation(Type)
;你将对你所说的没有信心。
来自Java Language Specification, Section 8.9 :
Enum types (§8.9) must not be declared abstract; doing so will result in a compile-time error.
An enum type is implicitly final unless it contains at least one enum constant that has a class body.
It is a compile-time error to explicitly declare an enum type to be final.
Nested enum types are implicitly static. It is permissible to explicitly declare a nested enum type to be static.
在下一节中:
The body of an enum type may contain enum constants. An enum constant defines an instance of the enum type.
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.