0

do java enums are singleton?

for example :

public enum State {

ACTIVE(0),
PENDING(1),
DELETED(2),
}


State s = State.ACTIVE;
State s2 = State.PENDING;
State s3 = State.PENDING;

is java create new instances every time we use State.FOO ??

2
  • 1
    Your enum has exactly three instances (ACTIVE, PENDING and DELETED) (or would if it was valid code). It does not create new instances every time you reference it. If you had only one element in your enum, instead of three, it would be a singleton. Commented Dec 20, 2017 at 16:05
  • 1
    "Because there is only one instance of each enum constant, it is permitted 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." (JLS Sec 8.9.1) Commented Dec 20, 2017 at 16:07

1 Answer 1

9

Enums in java are classes with several constant instances of themselves. These are created like static final variables. Accessing an enum constant returns a reference to the enum constant. It does not create a new instance of the enum constant.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.