0

Can anyone explain this Syntax -

public abstract class Enum<E extends Enum<E>>

Why does this let us declare Enum as ?

Public enum XYZ {…}
Rads
  • 53
  • 1
  • 6
  • 1
    See [What are generics in Java?](https://stackoverflow.com/questions/7815528/what-are-generics-in-java). `XYZ` kinda gets turned into `class XYZ extends Enum` – user Jul 19 '20 at 19:59
  • 5
    "Why does this let us declare Enum as ?" It doesn't. The syntax for declaring enums is defined in the language spec. `Enum>` is a self-bounded generic type, meaning there is a type variable, E, which allows you to say that a method in an enum returns "the self type" (or accepts an instance of itself as a parameter). It's also used e.g. in Comparable. – Andy Turner Jul 19 '20 at 20:08
  • The grammar's defined [here](https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9) – user Jul 19 '20 at 20:12
  • Thank you @AndyTurner - your response made me look for self-bounded generic type and found this nice post (for anyone else who stumbles on this post and is looking for more details) - https://stackoverflow.com/questions/19588449/self-bounded-generics which has more details on self-bounded-generics and enums. Thank you !! Thank you “user”. (Not sure why I am not able to tag you) – Rads Jul 19 '20 at 21:05

1 Answers1

1

Why does this let us declare Enum as ?

It doesn't. The syntax for declaring enums is defined in the language spec.

Enum<E extends Enum<E>> is a self-bounded generic type, meaning there is a type variable, E, which allows you to say that a method in an enum returns "the self type".

Looking at the Javadoc, the only method which actually uses E is Class<E> getDeclaringClass(). Having E allows the return value on enum MyEnum to be a Class<MyEnum>.

It's also used e.g. in Comparable, where you use it to say that the compareTo method should only accept a parameter "of the same type".

Andy Turner
  • 137,514
  • 11
  • 162
  • 243