Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are java enum variables static? [duplicate]

Tags:

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;
}

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?

like image 947
Optional Avatar asked Jun 18 '13 10:06

Optional


2 Answers

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.

From the 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.

And in the next section:

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.

like image 111
Eric Jablow Avatar answered Oct 12 '22 23:10

Eric Jablow


How can I have two instances of Operations.SINGLE with different operation type?

The fundamental idea behind an enum is that there is one, and only one, instance of each of its members. This is what lets you safely compare them for equality, without fear that there's another SINGLE or MULTIPLE created in some other place.

If you want multiple instances of SINGLE, make it a class, not an enum. The fact that you made your enum mutable indirectly points in the same direction: using enum is a wrong choice in your situation.

like image 31
Sergey Kalinichenko Avatar answered Oct 13 '22 00:10

Sergey Kalinichenko