Friday, December 13, 2019

Enum Tricky Questions

Java enumis a kind of a compiler magic. In byte code, any enum is represented as a class that extends the abstract class java.lang.Enum and has several static members. Therefore, enum cannot extend any other class orenum: there is no multiple inheritance.

Class cannot extend enum, as well. This limitation is enforced by the compiler.

Here is a simple enum:

enum Color {red, green, blue}


This class tries to extend it:

class SubColor extends Color {}


This is the result of an attempt to compile class SubColor:

$ javac SubColor.java
SubColor.java:1: error: cannot inherit from final Color
class SubColor extends Color {}
                       ^
SubColor.java:1: error: enum types are not extensible
class SubColor extends Color {}
^
2 errors


Enum cannot either extend or be extended. So, how is it possible to extend its functionality? The key word is "functionality." Enumcan implement methods.


https://dzone.com/articles/enum-tricks-two-ways-to-extend-enum-functionality

No comments:

Post a Comment