MikeMY
MikeMY

Reputation: 61

Java Enum referencing another enum

I would like to be able to define an Enum class that would include another Enum as well as its own values. For example, :

public enum A {
    A1, A2, A3;
}

public enum B{
    B1, B2, ...(somehow define references to all values in enum A)
}

such that any values contained in enum B must be either defined initself (such as B1, B2) or any values of enum A.

Thanks,

Upvotes: 6

Views: 20669

Answers (4)

jhhurwitz
jhhurwitz

Reputation: 89

Typically, since we are working in java, and usually proscribe to OO design, you could get this functionality through extension. However, enums extend java.lang.Enum implicitly and therefore cannot extend another class.

This means extensibility for enums most be derived from a different source.

Joshua Bloch addesses this in Effective Java: Second Edition in item 34, when he presents a shared interface pattern for enums. Here is his example of the pattern:

   public interface Operation {
        double apply(double x, double y);
    }

    public enum BasicOperation implements Operation {
        PLUS("+") {
            public double apply(double x, double y) { return x + y; }
        },
        MINUS("-") {
            public double apply(double x, double y) { return x - y; }
        },
        TIMES("*") {
            public double apply(double x, double y) { return x * y; }
        },
        DIVIDE("/") {
            public double apply(double x, double y) { return x / y; }
    }

This is about as close as you can get to shared state when it comes to enums. As Johan Sjöberg said above, it might just be easiest to simply combine the enums into another enum.

Best of luck!

Upvotes: 2

josefx
josefx

Reputation: 15656

The closest you can get is to have A and B implement some shared interface.

enum A implements MyEnum{A1,A2}
enum B implements MyEnum{B1,B2}

MyEnum e = B.B1;

This solution wont work with the switch statement nor with the optimised enum collections.

Your use-case is not supported by the java enum implementation, it was either to complex to implement (compared to its usefulness) or it didn't come up (none of the few languages that I know support this directly).

Upvotes: 1

ILMTitan
ILMTitan

Reputation: 11017

Something like this?

enum A {
    A1, A2;
}

enum B {
    B1(null),
    B2(null),
    A1(A.A1),
    A2(A.A2);

    private final A aRef;
    private final B(A aRef) {
        this.aRef = aRef;
    }
}

Upvotes: 3

Johan Sjöberg
Johan Sjöberg

Reputation: 49187

Such that B is the union of A and B? That's not possible without B extending A, which is not supported in java. The way to proceed is to create an enum which contains the combined values of A and B, e.g.,

enum C {
    A1, A2, A3, B1, B2;
}

Upvotes: 5

Related Questions