views:

245

answers:

3

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?

+20  A: 

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;
}
Thomas Lötzer
+1 I used this many times but I didn't know this was a pattern and had a name.
Bruno Rothgiesser
isn't it more an idiom than a pattern ?
Tom
+3  A: 

Search for builder pattern or fluent interface on google to have more details about this.

Return 'this' at the end of your method can do the trick in most cases.

Guillaume
A: 

From your example:

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

Each method in the chain has to return a class or an interface. The next method in the chain has to be a part of the returned class.

We start with Toast. The method makeText, which is defined as a static method in the class Toast, has to return a class or an interface. Here, it returns an instance of the class Gravity.

The method setGravity, which is defined in the class Gravity, returns an instance of the class View,

The method setView, which is defined in the class View, returns an instance of the class JPanel.

This chain could be written out step by step.

Gravity gravity = Toast.makeText(text);
View view       = gravity.setView(Gravity.TOP, 0, 0);
JPanel panel    = view.setView(layout);
panel.show();

Writing the chain as a chain removes all of the intermediate instance variables from the source code.

Gilbert Le Blanc
Local variables rather than instance? And they must still be there, they just don't have names any more.
pdbartlett