Hi, 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.
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 ]
Hi, 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.
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<?>
Post by:autobot
If you two don't stop this rough-housing somebody is going to end up crying. Sit down and read this tiny ad:
a bit of art, as a gift, the permaculture playing cards