java - java枚举变量是静态的吗?

标签 java enums

<分区>

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 实例?

最佳答案

是的,实例是隐式的 staticfinal。这意味着代码是不明智的。想象一下,两个线程都调用 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.

关于java - java枚举变量是静态的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17166668/

相关文章:

java - AudioInputSream 给出 nullPointerException

java - MongoDB Java驱动程序更新子文档

objective-c - 使用枚举将类型分配给一系列整数?

c# - 是否可以映射到带有别名的枚举?

java - 可以从 Java 中该类的枚举中访问类方法吗?

java - Path.equals 方法说明

java - 获取类的方法

Java 8 流 : convert comma separated string to the list of abstract Enum

c - 何时(不)使用 equal 创建枚举?

java - Java DateTime 中的 Duration.between() 返回负值时