There are some good people who appreciate the real value brought by Generics. But even fewer actually know or fully understand what purpose do self-bound generics really serve. The expression looks quite hazy at first and might make your head go spin if you begin wondering with utterly different but naturally occurring thoughts that may come to your mind while looking at the expression. It looks like this:
interface FooType<T extends<FooType<T>>
Looks like a mirrored expression which absolutely gives you no idea how deep the rabbit hole goes. Some people complain that generics have destroyed the simplicity of Java. But, I would argue that any useful language tends to grow a bit more complex as it goes through a constant process of evolution.
So, let’s see how in this world is this confusing recursive expression any useful at all. Some of you must have seen this expression being used in java.lang.Enum type-definition like this:
abstract class Enum<E extends Enum<E>>
Some of you might be thinking that simply Enum<E> would’ve sufficed for better type-safety but it turns out that controlling the implementing types or sub-types, sometimes, becomes necessary. For those times, the self-bound or recursive generic types come to the rescue.
To imagine what kind of control do self-bound generic types provide to the super-type, just think about the bounded generic types (non recursive) and what’s their significance. For example Foo<T extends SomeType> means that whatever type Foo holds, has state-properties and attributes defined by ‘SomeType’. So intuitively, a self-bound generic type would simply mean that all the state-properties and attributes would be defined by the holding type itself. Now this is the key to understand the real significance behind self-bound generics. The famous getThis() technique would also work without self-bound generic types (which is contrary to what some people believe) but when, for example, you are trying to encapsulate the behavior (a.k.a Strategy pattern from GoF) the self-bound generic types bring a great deal of flexibility.