java枚举变量是否静态? [英] Are java enum variables static?

查看:153
本文介绍了java枚举变量是否静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the above code, the value of operation changes for both the Operations. How can I have two instances of Operations.SINGLE with different operation type?

推荐答案

是的,实例是隐式 static final 。这意味着代码是不明智的。想象一下,两个线程都调用 SINGLE.setOperation(Type);你不会对你所说的话感到信心。

Yes, instances are implicitly static and final. This means that the code is unwise. Imagine two threads both calling SINGLE.setOperation(Type); you will have no confidence in what you are calling.

Java语言规范第8.9节


枚举类型( §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.

将枚举类型明确声明为final,这是一个编译时错误。

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.

因为每个枚举常量只有一个实例,所以允许使用==运算符代替如果已知至少有一个引用枚举常数,则比较两个对象引用时的equals方法。

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枚举变量是否静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆