Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Java notation

Tags:

java

android

I am trying to use dialogs in Android. In the process, I encountered lines of code like the following:

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

This notation is a bit strange for me as an old C++ programmer. Is this the same as,

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

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

like image 758
adba Avatar asked May 14 '26 04:05

adba


2 Answers

This idiom is called method chaining and it's not specific to Java or Android. The trick is making methods that otherwise would return void return a reference to this, permitting long chains of method calls to the same object.

This idiom is quite useful when used in the builder pattern, like in your example. It's also a building block when designing fluent interfaces.

like image 169
Joni Avatar answered May 15 '26 17:05

Joni


You can do same with C++ as well just return same object (this pointer). So ultimately you are calling next function on returned this pointer.

It is used in Builder Design Pattern!

like image 39
Prakash Avatar answered May 15 '26 17:05

Prakash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!