What is method chaining?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for OOP Concepts development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Method chaining is a technique where multiple methods are called on the same object in a single statement, each method returning this (or a new object). This creates a fluent interface that reads like a sentence. Builder pattern with method chaining: class QueryBuilder { private String table; private List<String> columns = new ArrayList<>(); private String whereClause; private String orderByClause; private Integer limit; public QueryBuilder select(String... columns) { this.columns.addAll(Arrays.asList(columns)); return this; // Return this for chaining } public QueryBuilder from(String table) { this.table = table; return this; } public QueryBuilder where(String condition) { this.whereClause = condition; return this; } public QueryBuilder orderBy(String column) { this.orderByClause = column; return this; } public QueryBuilder limit(int n) { this.limit = n; return this; } public String build() { return "SELECT " + String.join(", ", columns) + " FROM " + table + (whereClause != null ? " WHERE " + whereClause : "") + (orderByClause != null ? " ORDER BY " + orderByClause : "") + (limit != null ? " LIMIT " + limit : ""); } } // Usage -- reads like SQL! String query = new QueryBuilder() .select("id", "name", "email") .from("users") .where("active = true") .orderBy("name") .limit(10) .build();. Real examples: Java Stream API (.filter().map().collect()), StringBuilder, Lombok @Builder, most SQL query builders (Hibernate Criteria API, jOOQ), HTTP client builders. Benefits: readable code, less repetition, fluent API design. Immutable chaining: each call returns a new object (functional style) — for immutable types.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.