Forums Register Login

Enum can not be subclassed

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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<?>
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
https://gardener-gift.com


reply
reply
This thread has been viewed 5099 times.
Similar Threads
enum
enum within a method?
enum doubt
about enum
Strange Enum
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 23:26:42.