0

It is hard for me to understand the simulated self type idiom

abstract class Foo<T extends Foo>
{
    public abstract T doSomething();
}

and

abstract class Foo<T extends Foo<T>>
{
    public abstract T doSomething();
}

In both cases doSomething() returns a type which is Foo or a sub type of Foo

So basically it says that the type parameter of T must extend Foo or be Foo. Where do I need now the Foo<T> or in which cases do I need the second one instead of the first one? What do I am missing out?

I am looking for cases where the first one would not work but the second one would.

  • 3
    Are you aware of what a [raw type](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) is? The `Foo` in the first code snippet is a raw type. – Sweeper May 23 '21 at 13:17
  • Sure, I know it is a raw type. But still it is a `Foo` and would satisfy the doSomething() method. Honestly, I don't understand the self type idiom. – Michael Schulz May 23 '21 at 13:19
  • @MichaelSchulz then you do not know what a raw type is, because `Foo` is a raw type. In the rawtype, `T` could be a `Foo`, leading to unexpected behaviour. – Turing85 May 23 '21 at 13:20
  • I know that Foo itself is a Rawtype because it is missing the concrete Type of Foo. Just as rawtype List. Which would allow adding different objects at compile time. Why could it be Foo as T is bound to be a subtype of T – Michael Schulz May 23 '21 at 15:06
  • So the only purpose of the Selfreferencing Type Parameter is to prevent usage raw types? – Michael Schulz May 23 '21 at 15:34

0 Answers0