r/java • • Apr 05 '23

Recursive generics

Recently I learned that I rediscovered recursive generics while working on my pet open source project. Actually, I did not know that the construct had a name. I created small story about what this construct is, if you did not know about it java-recursive-generics

169 Upvotes

44 comments sorted by

View all comments

7

u/ukbiffa Apr 05 '23

Although not foolproof for fluent this typing:

public static class A<T extends A<T>> {
    public T doIt() {
        return (T) this;
    }
}
	
public static class B extends A<B> {}
	
public static class C extends A<B> {}
	
public static void main(String[] args) {
    new B().doIt().doIt();
    new C().doIt().doIt();
}

2

u/padreati Apr 06 '23

Right. You have to follow convention and pass the proper type.