File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Enum can not be subclassed Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Enum can not be subclassed" Watch "Enum can not be subclassed" New topic

Enum can not be subclassed

Kartik Patel
Ranch Hand

Joined: Sep 12, 2005
Posts: 73
I was going through J2SE1.5 features and one of the exciting feature I found was Enum.

The very first question came into my mind is :

Why Enum can not be sub classed explicitly? i.e Why can't i write a class which extends java.lang.Enum. it is an abstract class. Ideally it should allow me to extend. I have not seen such behavior from Java yet.

Chop your own wood, and it will warm you twice. - Henry Ford
Bupjae Lee
Ranch Hand

Joined: May 14, 2007
Posts: 107
If you declare with enum keyword, java compiler will automatically extends java.lang.Enum class and support all things regarding enum. (such as switch keyword support, singleton behavior, etc.)

There is some reasons why java forbid extending java.lang.Enum class explicitly.

* If user explicitly extends java.lang.Enum, enum objects are not guaranteed to singleton behavior (i.e. user can easily create more than one object about one enum constants)
* Java compiler make code implicitly for enum class such as enabling switch keyword, serializing, and such like that. These supportment relies whether object is instanceof java.lang.Enum and their implicitly code.
[ May 14, 2007: Message edited by: Bupjae Lee ]
Ritesh Sonawala

Joined: May 15, 2007
Posts: 1
The thing is i understand why they have done it, but its the way they have done it is difficult to digest.
Like declaring a class abstract and still not allowing it to be subclassed is certainly not the java way of doing something.
There could have been away in language itself to prevent this from subclassed...I am just trying to understand why they would have taken this approach.
Bupjae Lee
Ranch Hand

Joined: May 14, 2007
Posts: 107
In my opinion, they want to share same method without making redundancy code in class file such as toString(), equals(), clone() etc., but they don't want to extend by user because I mentioned above.

Moreover, there is special serializing process for enum constants. Before serializling, it checks whether object is enum by "if(obj instanceof java.lang.Enum)" (this is not same as "if(obj.getClass().isEnum())")

ps) Another similar example is Object.getClass()
For example:

If compiler were treated getClass() with other method, this would produce compiler time error, since return type of getClass() should be Class<?>
I agree. Here's the link:
subject: Enum can not be subclassed
It's not a secret anymore!