Video in progress
How do you write a Builder in an inheritance hierarchy so that the child builder's methods return the right type in a chain?
You use a generic "self type": Builder<T extends Builder<T>>, and every setter returns self(). The child builder passes itself as T, so child methods can still be called after a parent method.
📖 Answer
A plain builder breaks under inheritance:
new EmailNotification.Builder()
.to("a@b.uz") // returned Notification.Builder
.subject("Salom") // error: Notification.Builder has no subject()
With a self type:
public abstract class Notification {
private final String to;
protected abstract static class Builder<T extends Builder<T>> {
private String to;
public T to(String to) { this.to = to; return self(); }
protected abstract T self();
public abstract Notification build();
}
protected Notification(Builder<?> b) { this.to = Objects.requireNonNull(b.to); }
}
public final class EmailNotification extends Notification {
private final String subject;
public static final class Builder extends Notification.Builder<Builder> {
private String subject;
public Builder subject(String s) { this.subject = s; return this; }
@Override protected Builder self() { return this; }
@Override public EmailNotification build() { return new EmailNotification(this); }
}
private EmailNotification(Builder b) { super(b); this.subject = b.subject; }
}
Now new EmailNotification.Builder().to("a@b.uz").subject("Salom").build() compiles. The JDK uses this pattern too: Enum<E extends Enum<E>>.
The cost is a lot of code and generics that are hard to read. In Lombok, @SuperBuilder generates exactly this. But first ask yourself whether you need inheritance for notification types at all. Often a sealed interface with a separate record per type, or a plain constructor, turns out simpler.
Sign up to mark studied questions and save your progress.