Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a single enum value out of many types possible

Tags:

java

enums

I need to make a Java class which can receive a single enum value out of many. For example:

public class MyClass
{
    public enum enumA {..}
    public enum enumB {..}
    public enum enumC {..}
    public enum enumD {..}

    private OneOfTheEnumsAboveMember enumMember;
}

Since enums can't be extended, how can I define a single member which must be one of the enums?

like image 957
Yonatan Nir Avatar asked Mar 04 '16 09:03

Yonatan Nir


1 Answers

Enums cannot be extended, but they can implement interfaces. You could have an empty marker interface (or better yet - have it include methods you actually need), and make that the type of your member:

public class MyClass {
    public static interface EnumInterface {}
    public enum enumA implements EnumInterface {..}
    public enum enumB implements EnumInterface {..}
    public enum enumC implements EnumInterface {..}
    public enum enumD implements EnumInterface {..}

    private EnumInterface enumMember;
}
like image 107
Mureinik Avatar answered Oct 17 '22 05:10

Mureinik