Recently i have been asked a fairly simple question. “Can you extend an enum?”. My reaction to that was “Why would you want to do that?”. But, given a second thought, i realized that i didn’t really know the answer.
Of course i knew that in Java enums are treated as classes, but i had no clue how they look like inside the JVM, whether they were made final or not. I could of course try to extend an enum in IntelliJ and see whether the IDE would give me an error or not.
However, the correct way is to inspect how the class looks like after it gets deconstructed back from its bytecode. This can be done using the javap utility which comes along with the JDK. For example imagine we have the following enum:
Using the javap utility we can dissasemble the .class file, which will not give us the above result.
The class that the JVM knows is:
Finally we got our answer. The enums are indeed represented as classes inside the JVM and those classes are final, hence we cannot extend them.