Forums Register Login

Java Generic Enum Declaration - meaning and consequence

+Pie Number of slices to send: Send
In Java, the enum class is declared like this -



I was trying to understand the <E extends Enum<E>> part in the declaration. After reading this post from stackoverflow and this Angelika Langer faq, I understand that it's declared this way because the supertype wants to return object of subtypes from its method implementation (from the getDeclaringClass method), and also it wants to take a subtype as its argument in the compareTo method. As a result, it bound the parameter to itself. Also, the first answer of that stackoverflow post says -

It means that the type argument for enum has to derive from an enum which itself has the same type argument. How can this happen? By making the type argument the new type itself.



I don't understand this part. It says that because of the way the type parameter is declared, the new type should pass itself as a type parameter when extending from Enum class. But what's stopping me to pass another subtype of enum as a parameter instead of the new type being defined, like this -



So recursive generic bounds like this only ensures that the type argument that is passed to it are its subtypes, but it doesn't prevent mixing of its subtypes like I did in the second example.

Am I right, or I am missing something here?
+Pie Number of slices to send: Send
Well, if you extended your definition as with Enum and defined a compareTo and a getDeclaringClass, you'd get something that would allow compareTo  from Car to Bus but not from Bus to Car, but not sure that helps answer your question (plus, it's been 4 years...)

+Pie Number of slices to send: Send
 

Md Sayem Ahmed wrote:But what's stopping me to pass another subtype of enum as a parameter instead of the new type being defined, like this


You can't extend Enum yourself, only by creating a proper enum. For instance:

But in your vehicle example there is nothing to prevent this unfortunately. With the exception of Enum it's not possible to enforce that the generic type is the class itself.
+Pie Number of slices to send: Send
Thanks for the clarification. I think I had missed the point of the original question.
Put a gun against his head, pulled my trigger, now he's dead, that tiny ad sure bled
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 3198 times.
Similar Threads
converting a string color to an object color
In The Matrix with Enums and Constructors
Simple J2SE 5.0 Tiger Notes
Another confusing generic error
Creating a more generic DAO (no hibernate) - A good Riddle
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 13:38:15.