Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: anonymous enums?

Tags:

Does Java have the possibility of anonymous enums?

For example, I want my class to have one variable, whose value can be one of 5 different settings. So obviously that variable should be an enum. But this is the ONLY place where that particular enum will be used. Normally I would declare an enum type right above the variable and then declare the variable to be that type, but I was wondering if there is a cleaner way. Does Java support anonymous enums?

Example:

public class Test {
    public enum Option {
        FirstOption,
        SecondOption,
        ThirdOption
    }
    Option option;
}

Is there a way to avoid declaring public enum Option and instead simply allow the option variable to be set to either FirstOption, SecondOption or ThirdOption with no notion of the "Option" type?

like image 730
Ricket Avatar asked Jul 22 '10 01:07

Ricket


People also ask

What is anonymous enum?

An anonymous Enum is an unnamed enum.

Can enum be Typecasted?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.

Can enum have constructor Java?

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

What are enums in Java?

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum , use the enum keyword (instead of class or interface), and separate the constants with a comma.


1 Answers

No Java does not support anonymous enums.

Just declare them inside the class with no external visibility:

public class Test {
  private static enum Option {
    FirstOption,
    SecondOption,
    ThirdOption
  }

  Option option;
}
like image 52
cletus Avatar answered Sep 17 '22 08:09

cletus