Nesting enums in Java

前端 未结 3 1710
一个人的身影
一个人的身影 2021-02-14 06:33

I want to nest some enums. The object i\'m representing are Flags, with a type, and a value. There are a discrete number of types, and each type has a distinct set of possible v

相关标签:
3条回答
  • 2021-02-14 07:15

    As I understand enums, they are kind of singletons. It means enum X {A,B} has two singleton instances A,B. If you had nested enum A { P, Q }, how you can say if X.A is X.A.P or X.A.Q ? I wish I was able to say it more simply.

    Use static class.

    0 讨论(0)
  • 2021-02-14 07:17

    You cannot have a number as an enum. It has to be an identifier.

    You can do this

    interface Flag {
        String getType();
        int getValue();
        enum A implements Flag{
            one, two, three;
            String getType() { return getClass().getSimpleName(); }
            int getvalue() { return ordinal()+1; }
        }
        enum B implements Flag{
            four, five, six;
            String getType() { return getClass().getSimpleName(); }
            int getvalue() { return ordinal()+4; }
        }
    }
    
    Flag f = Flag.A.one;
    

    However a simpler option may be

    enum Flag {
        A1, A2, A3, B4, B5, B6;
        public String getType() { return name().substring(0,1); }
        public int getValue() { return name().charAt(1) - '0'; }
    }
    
    Flag f = Flag.A1;
    
    0 讨论(0)
  • 2021-02-14 07:24

    Nesting enums is not possible. But enums can implement interfaces. Why not have A and B as two different enums that both implement a TypedEnum interface with getType() and getValue() methods?

    0 讨论(0)
提交回复
热议问题