Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

How do covariant return types help with fluent builder APIs in a class hierarchy, and what alternative do recursive generics offer?

With covariant return types, a subclass builder can override each inherited setter to return its own type, so a chain like name(...).subject(...) keeps access to the subclass's methods. The cost is overriding every method only to change its return type. Recursive generics, Builder<T extends Builder<T>> with an abstract self() method, let the base class return T so no overrides are needed, at the price of harder-to-read signatures; for small hierarchies, covariant overrides or separate builders are often simpler.

Why this question is asked

Fluent builders are everywhere in Java code: HTTP clients, test data, configuration objects and domain objects with many optional fields. As soon as builders form a hierarchy, for example a base notification builder with email and SMS builders below it, the chain breaks in a surprising way. Interviewers ask about it because it combines two language features, covariant returns and generics, with a practical design trade-off. In this answer, we will reproduce the broken chain, fix it with covariant overrides, fix it again with recursive generics, and then compare the two so we can choose sensibly.

1A Quick Recap of Fluent Builders

A fluent builder is an object whose setter-like methods return the builder itself, so calls can be chained and the final build() call creates the real object. A covariant return type, which we will rely on, means an overriding method may declare a more specific return type than the method it overrides. Our example has a base builder for any notification and a subclass for emails, which adds a subject.

2Reproducing the Broken Chain

Here is the naive hierarchy. Each base setter returns this, typed as the base builder.

Java
class NotificationBuilder {
protected String recipient, body;
NotificationBuilder recipient(String r) { this.recipient = r; return this; }
NotificationBuilder body(String b) { this.body = b; return this; }
}
class EmailBuilder extends NotificationBuilder {
private String subject;
EmailBuilder subject(String s) { this.subject = s; return this; }
Email build() { return new Email(recipient, subject, body); }
}
new EmailBuilder().subject("Hi").recipient("a@x.io").build(); // compile error
// recipient(...) returns NotificationBuilder, which has no build() method

The object at run time is still an EmailBuilder, but the compiler only knows the declared return type of recipient(), which is NotificationBuilder. So after the first base method, the chain loses every subclass method. Callers can work around it by ordering calls carefully, subclass methods first, but that is fragile and confusing.

3Fix 1: Covariant Overrides in the Subclass

Since Java 5, the subclass may override each base method and narrow its return type to EmailBuilder. The override does nothing new; it calls super and returns this with the more specific type.

Java
class EmailBuilder extends NotificationBuilder {
private String subject;
@Override EmailBuilder recipient(String r) { super.recipient(r); return this; }
@Override EmailBuilder body(String b) { super.body(b); return this; }
EmailBuilder subject(String s) { this.subject = s; return this; }
Email build() { return new Email(recipient, subject, body); }
}
Email e = new EmailBuilder().recipient("a@x.io").subject("Hi").body("...").build(); // compiles

This is simple to understand: each method's signature says exactly what it returns. But there is a catch. Every subclass must override every base method, only to change the return type. With ten base methods and four subclasses, that is forty boilerplate overrides, and when someone adds an eleventh base method and forgets an override, the chain silently breaks again for that method.

4Fix 2: Recursive Generics and self()

Recursive generics, sometimes called the curiously recurring template pattern or a self type, let the base class know the subclass's type. The base builder takes a type parameter T that must itself be a builder of T, and returns T from every setter by calling an abstract self() method.

Java
abstract class NotificationBuilder<T extends NotificationBuilder<T>> {
protected String recipient, body;
T recipient(String r) { this.recipient = r; return self(); }
T body(String b) { this.body = b; return self(); }
protected abstract T self();
}
final class EmailBuilder extends NotificationBuilder<EmailBuilder> {
private String subject;
@Override protected EmailBuilder self() { return this; }
EmailBuilder subject(String s) { this.subject = s; return this; }
Email build() { return new Email(recipient, subject, body); }
}
Email e = new EmailBuilder().recipient("a@x.io").subject("Hi").build(); // compiles, no overrides

The reason self() exists is that the base class cannot simply return (T) this without an unchecked cast. Each concrete subclass returns this, and the compiler checks that the type matches. Now adding a new base method automatically works for every subclass, because it returns T.

Notice what it costs. Signatures like NotificationBuilder<T extends NotificationBuilder<T>> are hard to read for many developers, error messages become longer, and code that wants to hold any builder must write NotificationBuilder<?>. A deeper hierarchy, where a middle class must stay generic, needs its own type parameter passed down as well.

5Choosing Between the Two

The choice depends mainly on how many builders and base methods we have, and who will read the code.

Fluent builders in a hierarchy
ApproachGood whenCost
Covariant overridesOne or two subclasses, few base methodsBoilerplate overrides; easy to forget one
Recursive genericsMany subclasses or a public libraryHard-to-read signatures, wildcard types
Separate buildersSubtypes share littleSome duplicated setters
Generated (Lombok @SuperBuilder)Team already uses LombokGenerated code hidden from readers
There is no single right answer; the decision is about scale and readability.

For two subclasses, covariant overrides are often the most honest choice, because every signature is plain. For a library with many builder types, recursive generics save a lot of maintenance and users rarely see the generic signature. And often the best option is to question the hierarchy: if an email and an SMS share only a recipient and a body, two independent builders with a little duplication may be clearer than any inheritance.

6Follow-up questions

Why not just cast in the base class with (T) this?

It works at run time but produces an unchecked cast warning, and nothing stops a subclass from declaring the wrong type argument, for example class SmsBuilder extends NotificationBuilder<EmailBuilder>. The self() method moves the decision into each concrete class, where the compiler checks that this really is a T.

Where does the JDK use recursive generics?

The best-known case is Enum<E extends Enum<E>>, which lets compareTo and getDeclaringClass work with the specific enum type. Comparable-like bounds such as T extends Comparable<? super T> are related but not the same pattern.

Do records change this design?

Records cannot extend classes, so hierarchies of record builders are not possible in the usual way. With records we often use a sealed interface for the variants and a separate small builder or static factory for each record, which avoids the problem entirely.

7Conclusion

In this answer, we saw that a builder hierarchy breaks fluent chains because base methods return the base type. Covariant overrides fix it by narrowing each inherited method's return type, at the cost of overriding every method. Recursive generics with Builder<T extends Builder<T>> and a self() method fix it once in the base class, at the cost of harder signatures. For small hierarchies, covariant overrides or separate builders are often the simpler and clearer choice.

What to say in the interviewAbout 80 seconds aloud

Open with

In a builder hierarchy, the problem is that base class setters return the base type, so after calling recipient on an EmailBuilder the compiler only sees a NotificationBuilder and the chain loses subject and build.

Then, if they want more

Covariant return types give one fix: the subclass overrides each inherited setter, calls super and returns this typed as EmailBuilder. It's simple and every signature is plain, but every subclass has to override every base method just to change the return type, and if someone adds a base method and forgets an override, that method breaks the chain.

The other option is recursive generics. The base class is declared as NotificationBuilder of T extends NotificationBuilder of T, every setter returns T by calling an abstract self method, and each concrete builder extends NotificationBuilder of itself and returns this from self. Then new base methods work everywhere with no overrides.

The cost is readability: the signatures confuse people, error messages get long, and holding any builder needs a wildcard. So my choice depends on scale. For a couple of subclasses I'd use covariant overrides or even separate builders if they share little. For a library with many builder types, recursive generics, or Lombok's SuperBuilder if the team already uses Lombok.

About this answer

Last updated
12 November 2026
Versions it names
Java 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do covariant return types help with fluent builder APIs in a class hierarchy, and...": https://scrivio-interview-library.netlify.app/java/oop-principles/63d672d027/