How to do method chaining in Java? o.m1().m2().m3().m4()

Pentium10 picture Pentium10 · May 20, 2010 · Viewed 31.8k times · Source

I've seen in many Java code notation that after a method we call another, here is an example.

Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(layout).show();

As you see after calling makeText on the return we call setGravity and so far

How can I do this with my own classes? Do I have to do anything special?

Answer

Thomas Lötzer picture Thomas Lötzer · May 20, 2010

This pattern is called "Fluent Interfaces" (see Wikipedia)

Just return this; from the methods instead of returning nothing.

So for example

public void makeText(String text) {
    this.text = text;
}

would become

public Toast makeText(String text) {
    this.text = text;
    return this;
}