javaoopinterfacetype-bounds

Interface type parameter extends the interface?


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?


Solution

  • 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.