Java generic type

Yes, this can be done (sort of; see below). (In the C++ world, this is called the “Curiously Recurring Template Pattern“, but it applies in Java too):

public interface Recur<T extends Recur<T>> {
    // ...
}

(Note the second mention of T. That’s an essential part of the CRTP.)

Also, this is how java.util.Enum is defined, so that an enum type called Foo must derive from Enum<Foo>, so it’s not an uncommon pattern in Java either.


I’d like to say that the above is the end of the story, but tangens rightly points out in their revision that it’s not totally robust, and really not all that different from their answer in character.

There is one difference (that I can think of) between the Recur<T> solution I have, and the Recur<?> solution that tangens has:

public interface Recur<T extends Recur<T>> {
    T foo();
}

class A implements Recur<B> {
    @Override
    public B foo() {
        return new B();
    }
}

class B implements Recur<A> {
    @Override
    public A foo() {
        return new A();
    }
}

With <T>, the above would not compile; with <?>, it would. But that’s just splitting hairs; it doesn’t change tangens’s central point which is that given an already valid Recur implementation, you can make subsequent implementations use the already-valid type, rather than itself. I still say that’s worth something, but that’s not worth any more of a something than tangens’s answer.

In closing, go ahead and upvote tangens’s answer too, if you can. (tangens, you should touch your post so I can upvote you too.) They have a very good point, and I’m sorry that I missed it the first time around. Thanks, tangens!

Leave a Comment