Shadab
Shadab

Reputation: 51

java enum type instantiation

Are there any objects created respective to each of the enum constants ARROGANT, RASCAL, IDIOT?

public enum Manager {
    ARROGANT,
    RASCAL,
    IDIOT
}

and if the following code does the same as the above, explicitly though,

public enum Manager {
    ARROGANT(),
    RASCAL(),
    IDIOT();

    Manager() {}
}

Upvotes: 5

Views: 2799

Answers (2)

josefx
josefx

Reputation: 15656

Yes, both should result in the same bytecode, the first is only syntactic sugar.

The second is useful when you have to associate values with an enum.

enum Numbers{
    ONE(1),TWO(2),THREE(3),TEN(10);
    Numbers(int i){
       value = i;
    }
    public final int value;
}

Upvotes: 4

Joachim Sauer
Joachim Sauer

Reputation: 308041

Yes, exactly one instance will be created for each enum constant.

And yes, the second sample code is effectively identical.

Upvotes: 6

Related Questions