When I have an interface
public interface Foo<T> {
T someMethod();
}
is there any way to assure that when some class implements this interface then generic type is the same implementig class.
For example:
public class Bar implements Foo<Bar> {
Bar someMethod() {
return new Bar();
}
}
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):
(Note the second mention of
T. That’s an essential part of the CRTP.)Also, this is how
java.util.Enumis defined, so that an enum type calledFoomust derive fromEnum<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 theRecur<?>solution that tangens has: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 validRecurimplementation, 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!