开发者

Java: anonymous enums?

开发者 https://www.devze.com 2023-01-08 03:03 出处:网络
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

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?


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

精彩评论

暂无评论...
验证码 换一张
取 消