DEV Community


Method Chaining In Java

skptricks profile image skptricks ・1 min read

Post Link :

The term method chaining refers to both a design and a convention. Each method returns an object, allowing the calls to be chained together in a single statement. Chaining is syntactic sugar which eliminates the need for intermediate variables. A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together even though line breaks are often added between methods.

class User {

private String name;
private int age;

// In addition to having the side-effect of setting the attributes in question,
// the setters return "this" (the current Person object) to allow for further chained method calls.

public User setName(String name) { = name;
return this;

public User setAge(int age) {
this.age = age;
return this;

public void getUserDetails() {
System.out.println("User name is " + name + " and " + age + " years old.");

// Usage:
public static void main(String[] args) {
User user= new User();


Ouput :
User name is skptricks and 22 years old.

Discussion (1)

Editor guide
firuzzz profile image
Jose Luis Romero

So... U just copy/paste articles? A very bad one btw, with a horrible example of pipeline pattern which doesn't show its strength or expose its weakness
Java has hundreds of well design patterns like StringBuilder, all Stream implementation