Builder: required fields in the constructor, optional in setters

Not every builder needs a separate Builder class: putting the fields that must always be supplied in the constructor, and letting chained setters fill in the rest, still forces callers to provide the essentials while keeping the optional ones fluent.

Code
class Coordinate {
    private final double lat, lon;
    private String label = "unnamed";
    Coordinate(double lat, double lon) { this.lat = lat; this.lon = lon; }
    Coordinate label(String l) { label = l; return this; }
    public String toString() { return label + " (" + lat + ", " + lon + ")"; }
}
Coordinate point = new Coordinate(12.9, 77.6).label("Office");
System.out.println(point);
Output
Office (12.9, 77.6)
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