Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Self Bound or Recursive Generics

 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.

BR,
 
Stephan van Hulst
Bartender
Pie
Posts: 5407
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Prithvi,

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:
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Stephen,

I am talking about this DecryptEnum

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.

BR,
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, Stephen,

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()

BR,
 
Stephan van Hulst
Bartender
Pie
Posts: 5407
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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>>.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic