Nesting enums in Java

Viewed 11126

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 values.

So if Type A can have values 1, 2 or 3, and Type B can have values 4,5,6, I'd like to be able to do things like:

Flag f = Flag.A.1;

f.getType() - returns "A"

f.getValue() - returns "1"

Flag f2 = Flag.A.4; -- Syntax error.

I'm driving myself crazy trying to nest enums within enums - is what i'm trying possible - do I need to ditch enums altogether and handcraft a static class with static members?

My best effort so far is:

public class Flag {

    enum A extends Flag {
        ONE("ONE"),
        TWO("TWO"),
        THREE("THREE");

        private A(String value) {
            Flag.type = "A";
            Flag.value = value;
        }
    }

        private static String type;
        private static String value;
}

But if I do:

Flag f = Flag.A.ONE;

The types are incompatible.

3 Answers
Related