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?
An anonymous Enum is an unnamed enum.
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.
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.
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.
No Java does not support anonymous enum
s.
Just declare them inside the class with no external visibility:
public class Test {
private static enum Option {
FirstOption,
SecondOption,
ThirdOption
}
Option option;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With