简体   繁体   English

为什么我不能在 Java 的内部类中创建枚举?

[英]Why can't I create an enum in an inner class in Java?

What I try to do is this:我尝试做的是:

public class History {
    public class State {
        public enum StateType {

Eclipse gives me this compile error on StateType : The member enum StateType must be defined inside a static member type . Eclipse 在StateType上给了我这个编译错误: The member enum StateType must be defined inside a static member type

The error disappears when I make the State class static.当我将State类设为静态时,错误就会消失。 I could make State static, but I don't understand why I cannot declare an enum in an inner class.我可以将State设为静态,但我不明白为什么我不能在内部类中声明enum

enum types that are defined as nested types are always implicitly static (see JLS §8.9. Enums )定义为嵌套类型的enum类型始终是隐式static (参见JLS §8.9. Enums

You can't have a static nested type inside a non-static one (aka an "inner class", see JLS §8.1.3. Inner Classes and Enclosing Instances ).您不能在非静态类型中包含静态嵌套类型(也称为“内部类”,请参阅JLS §8.1.3. 内部类和封闭实例)。

Therefore you can't have an enum inner type inside a non-static nested type.因此,您不能在非静态嵌套类型中使用enum内部类型。

If you declared an enum like this:如果您声明了这样的枚举:

enum Suit {SPADES, HEARTS, CLUBS, DIAMONDS}

The Java compiler would synthetically generate the following class for you: Java 编译器将为您综合生成以下类:

final class Suit extends java.lang.Enum<Suit> {
  public static final Suit SPADES;
  public static final Suit HEARTS;
  public static final Suit CLUBS;
  public static final Suit DIAMONDS;
  private static final Suit[] $VALUES;
  public static Suit[] values();
  public static Suit valueOf(java.lang.String);
  private Suit();
}

There is no intention to create other instances of this class other than those static fields already defined in it (as you could infer from its private constructor), but most importantly, and as mentioned in the accepted answer, a inner class cannot have static members ( JLS §8.1.3. Inner Classes and Enclosing Instances ), and since the enum synthetic class does, it makes it unacceptable as inner class.除了已经在其中定义的那些静态字段之外,无意创建此类的其他实例(正如您可以从其私有构造函数中推断出的那样),但最重要的是,正如已接受的答案中所述,内部类不能具有静态成员( JLS §8.1.3. 内部类和封闭实例),并且由于枚举合成类确实如此,因此它作为内部类是不可接受的。

Already enough information from +Joachim Sauer, I am just adding some extra details. +Joachim Sauer 已经提供了足够的信息,我只是添加了一些额外的细节。

You can define inner enum only if your inner class is static nested inner class.只有当您的内部类是静态嵌套内部类时,您才能定义内部枚举。 See below见下文

private static class DbResource {

    public enum DB {
        MERGE_FROM, MERGE_TO, MAIN;
    }
}

This worked for my use-case:这适用于我的用例:

public class History {

    public interface HConstants{
         public enum StateType { PAST,CURRENT,FUTURE}
    }

    //Inner class
    public class State implements HConstants{
        public StateType stateField = StateType.PAST;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM