Java – Learn about Java symbols

Learn about Java symbols… here is a solution to the problem.

Learn about Java symbols

I’m trying to use dialogs in Android. In the process, I came across the following lines of code:

alertDialogBuilder
            .setMessage("Click yes to exit!")
            .setCancelable(false)
            .setPositiveButton("Yes",new...

As an old C++ programmer, this symbol is a bit strange to me. Is this related to ,

alertDialogBuilder.setMessage("Click yes to exit!");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Yes",new...

If so, is this notation part of Java or exclusive to Android programming? What is the name of this symbol (or method)?

Solution

This idiom is called method chaining, and it is not specific to Java or Android. The trick is to have methods that would otherwise return void return a reference to this, allowing for long chain method calls to the same object.

This idiom is useful when used in builder pattern, just like in your example. It is also a building block when designing< a href="http://en.wikipedia.org/wiki/Fluent_interface" rel="noreferrer noopener nofollow">fluent interfaces

Related Problems and Solutions