Zhro Zhro - 6 months ago 7
Java Question

How to use an enum as one would use an interface?

How can I assign SomeEnum1 or SomeEnum2 to an "enum" which implements SomeInterface? I can't just specify the interface directly as it's a class and not an enum.

I'm sure there is a specify syntactic sugar to make this work but I can't figure it out.

Example:

public class Main {
public interface SomeInterface {
public String doSomething();
}

public enum SomeEnum1 implements SomeInterface {
something1;

@Override
public String doSomething() {
return "SomeEnum1";
}
}

public enum SomeEnum2 implements SomeInterface {
something2;

@Override
public String doSomething() {
return "SomeEnum2";
}
}

public static void main(String[] args) {
// Works but not polymorphic
SomeEnum1 e1 = SomeEnum1.something1;
System.out.println(e1.name() + " " + e1.doSomething());

// Not an enum
// SomeInterface e2 = SomeEnum1.something1;
// System.out.println(e2.name() + " " + e2.doSomething());

// Bounds mismatch
// Enum<SomeInterface> e3 = SomeEnum1.something1;
// System.out.println(e3.name() + " " + e3.doSomething());
}
}

Answer

If you pass the value to a method, you can use generics to restrict the type of SomeInterface by 2 constraints:

public static void main(String[] args) {
    print(SomeEnum1.something1);
}

public static <T extends Enum & SomeInterface> void print(T t) {
    System.out.println(t.name() + " " + t.doSomething());
}
Comments