Builder: a fluent builder returns this from every setter

Each setter mutates the object's own fields and then returns this, so calls can be chained into a single expression instead of one statement per field. It is the pattern that lets a builder read like a small sentence.

Code
class Query {
    private String table = "";
    private String where = "";
    private int limit = 0;
    Query from(String t) { table = t; return this; }
    Query where(String w) { where = w; return this; }
    Query limit(int n) { limit = n; return this; }
    public String toString() { return "SELECT * FROM " + table + " WHERE " + where + " LIMIT " + limit; }
}
Query q = new Query().from("orders").where("total > 100").limit(10);
System.out.println(q);
Output
SELECT * FROM orders WHERE total > 100 LIMIT 10
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms