Can a Java enum implement a sealed interface?

421 views Asked by At

Can a Java enum implement a sealed interface in Java and why?

A sealed subclass must be final, sealed or non-sealed. My reasoning is that if an enum could implement a sealed interface it can only be non-sealed, because it cannot be marked final and it cannot be extended either, therefore it cannot be marked sealed.

I’m sorry if there is the answer somwhere but I can’t seem to find it.

1

There are 1 answers

3
rzwitserloot On

I have taken the 5 seconds required to test it:

Foo.java:

public sealed interface Foo permits Bar {}

Bar.java:

public enum Bar implements Foo {
  A, B {
    void baz() {}
  }
}

The enum even has effectively a subclass (the inner class representing B).

> javac *.java

compiles just fine, no complaints from javac.

From a mental model it makes perfect sense: An enum type quacks, walks, and swims like a final type: An enum cannot be extended by other code, only by recompiling it. Yes, an enum can be 'subclassed' (that's what B up there is doing: It makes a new anonymous class, more or less named Foo$B extends Foo, which includes that baz() method, and the JVM will make a singleton instance of that class. Except, of course, javac manages all this. You cannot actually get an actual source file with the actual letters class Foo$B extends Foo {} (where Foo is an enum) to be compiled with a javac that adheres to the spec.

It sounds like you were asking 'is it possible', in which case, [A] yes, and [B] I strongly suggest you just try this stuff; it'll take less time than writing an SO question and you learn more.

Perhaps you meant: "I think they should not, but javac allows it". In which case, that breaks down into 2 further variants: "... I am confused about why it is allowed" (the above explanation should then suffice to explain why), or "... I think the JLS is broken because the way I read it, you should not be able to do this". In which case, file a bug with openjdk project, if you want. But the bug is then in the JLS, not in javac: Being able to write the above is obviously the right intent.