Method chaining in the Builder pattern works by having each setter-style method return the builder instance itself, so multiple configuration calls can be strung together into a single fluent expression that ends with a build() call.
Key Points: • Each builder method sets one field and then returns `this`, enabling the next call to be chained immediately. • The chain terminates with a build() method that constructs and returns the final, often immutable, object. • It produces a fluent, readable API compared to a long parameter list or many separate setter calls. • Only the fields explicitly chained get set, with defaults applying to anything left out. • It works well alongside validation logic placed inside build() to check required fields before construction.
Example: Calling `new PersonBuilder().name("Amol").age(30).city("Pune").build()` reads naturally as a single statement, where each method call configures one field and hands control back to continue the chain.
Code Example:
class PersonBuilder {
private String name;
private int age;
PersonBuilder name(String name) {
this.name = name;
return this;
}
PersonBuilder age(int age) {
this.age = age;
return this;
}
Person build() {
return new Person(name, age);
}
}Interview Tip: A concise interview answer is:
"Method chaining works because every builder method sets a field and returns the builder object itself, letting you string calls together into one fluent expression that finishes with build(), which constructs the final object — it reads cleanly and avoids constructors with long parameter lists."