Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 288
Pentium10 Avatar asked May 20 '10 08:05

Pentium10


People also ask

How do you do method chaining in Java?

Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.).

What is chaining in programming?

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.


1 Answers

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; } 
like image 110
Thomas Lötzer Avatar answered Sep 22 '22 02:09

Thomas Lötzer