1

I came by this construction when reading a codebase and I can't figure out what it does/represents:

public interface MyInterface<T extends MyInterface<T>> {}

I don't understand what the type bound does here - it seems almost recursive? What's really the restriction on T in this case?

Nimrod Sadeh
  • 183
  • 9

1 Answers1

2

It means that any class that implements the interface must specify T as themselves:

class MyClass implements MyInterface<MyClass> {}
//       │                              ↑
//       └──────────────────────────────┘

Here T is MyClass, which extends MyInterface<MyClass>, so the T extends MyInterface<T> bound is satisfied.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • So basically any method that takes/gives T is actually taking/giving "this class"? For example: T someMethod(...) actually says "This method takes some parameters and gives some instance of the implementing class? I guess that is stronger than simply saying ```interface MyInterface { MyInterface foo(...) } ``` as that could be any implementation of MyInterface – Nimrod Sadeh May 18 '21 at 03:14
  • @NimrodSadeh No, you are not *guaranteed* that `T` is the type of the `this` object. E.g. `class Foo implements MyInterface {}` and `class Bar implements MyInterface {}` is valid, even though the `T` of `Bar` is not a type `Bar`. – Andreas May 18 '21 at 03:20