Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Fluent builder with self type

A generic self type keeps subclass-specific methods available after inherited fluent calls. The terminal `build()` call creates a separate product from the builder’s current state.

Version: Java SE 21

Syntax

Declaration sketch (method bodies omitted):
abstract class TaskBuilder<S extends TaskBuilder<S>> {
    protected abstract S self();
    public final S tag(String value) { /* mutate this builder, then return self() */ }
    public abstract Task build();
}
final class PriorityTaskBuilder extends TaskBuilder<PriorityTaskBuilder> {
    @Override protected PriorityTaskBuilder self() { return this; }
    @Override public PriorityTask build() { /* return a new product */ }
}
// PriorityTask extends Task.

A Fluent builder with self type lets you chain configuration calls on a mutable builder. tag(...) changes the current builder and returns that same instance through self(), not a copy or a finished product. Here == checks object identity, not equality of contents.

In TaskBuilder<S extends TaskBuilder<S>>, S appears in its own upper bound. PriorityTaskBuilder supplies itself as S, so the inherited tag(...) can be followed by priority(...). The abstract self() lets the concrete class return this without an unchecked cast. The bound alone requires neither that a subclass supply its own type nor that self() return the current instance.

The base declaration of build() returns Task. The builder subclass overrides it with the covariant return type PriorityTask, a subtype of Task; this is overriding, not overloading. Through the base reference, the result has static type Task, even though the subclass method still runs.

Each build() creates a new product that captures the current state. List.copyOf produces an unmodifiable list unaffected by later edits to the builder’s list. This is a shallow copy: String elements are immutable, but mutable elements would need additional defensive copies to isolate their state. tag(null) throws NullPointerException immediately, before the list changes.

Examples

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class FluentBuilderDemo {
    static class Task {
        private final List<String> tags;

        private Task(TaskBuilder<?> builder) {
            tags = List.copyOf(builder.tags);
        }

        public final List<String> tags() {
            return tags;
        }
    }

    static final class PriorityTask extends Task {
        private final int priority;

        private PriorityTask(PriorityTaskBuilder builder) {
            super(builder);
            priority = builder.priority;
        }

        public int priority() {
            return priority;
        }
    }

    static abstract class TaskBuilder<S extends TaskBuilder<S>> {
        private final List<String> tags = new ArrayList<>();

        protected abstract S self();

        public final S tag(String value) {
            tags.add(Objects.requireNonNull(value, "tag"));
            return self();
        }

        public abstract Task build();
    }

    static final class PriorityTaskBuilder extends TaskBuilder<PriorityTaskBuilder> {
        private int priority;

        @Override
        protected PriorityTaskBuilder self() {
            return this;
        }

        public PriorityTaskBuilder priority(int value) {
            priority = value;
            return self();
        }

        @Override
        public PriorityTask build() {
            return new PriorityTask(this);
        }
    }

    public static void main(String[] args) {
        PriorityTaskBuilder builder = new PriorityTaskBuilder();
        System.out.println(builder.tag("draft").priority(5) == builder);

        TaskBuilder<PriorityTaskBuilder> base = builder;
        Task first = base.build();
        PriorityTask second = builder.tag("review").build();

        System.out.println("first: " + String.join(", ", first.tags()));
        System.out.println("second: " + String.join(", ", second.tags()));
        System.out.println("priority: " + second.priority());
    }
}

Result

true
first: draft
second: draft, review
priority: 5

`true` confirms that the chain returns the same builder. Adding `review` affects the second result but not the first.

Related lessons

  • Java · Lesson 3 · Advanced · Version: 2
  • Java · Lesson 16 · Advanced · Version: 2

Sources