I am using a concept these days called Self bound or Recursive generics but i am not able to understand it.
Can someone explain that what is a recursive or self bound generics? Why we should use them and what is
the advantage? Looking forward for a pointer.
I assume you are referring to the declaration that looks something like this:
Here, the formal type parameter T is defined in terms of itself. It's actually less hard than it looks.
When you create an instance of First, it's actual type parameter must be something that extends Second<T>, where T is the same type as the actual type parameter.
Here's an example:
The use if this is that you can require types to accept or return values that are of their own type. An example of this is the Enum class. Enum requires its subclasses to return instances of themselves:
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
These are self-bound generics. So i am looking forward to know what advantage do they give and how simply we can decrypt this Enum thing.
Joined: Oct 13, 2009
This technique is more famously known as getThis() technique also. It is described here but i am unable
to understand this concept. Can you have a look at it and let me know what does this exactly mean.
Please check getThis()
Enum<E extends Enum<E>> basically means: "each enum must be an enum of its own type".
It more or less forces Enum subtypes to return instances of their own type, which makes sense.
I say more or less, because if Enum wasn't a special class in the Java language, it would be possible to make a declaration like this:. This however would still force Color to be an Enum<Color>, which is what it's all about.
If in Java you want subtypes of a type to return or accept instances of their own formal type, the general pattern is: X<T extends X<T>>.