9

What is the meaning of this .notation (AlertDialog.Builder) in a class constructor?

public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new AlertDialog.Builder(getActivity())
        .setTitle(R.string.date_picker_title)
        .setPositiveButton(android.R.string.ok, null)
        .create();

}

Does it mean that the Builder class is defined inside the AlertDialog class? Or Builder is a method, but its first letter is capitalized so I'm confused.

Machavity
  • 30,841
  • 27
  • 92
  • 100
Jezer Crespo
  • 2,152
  • 3
  • 24
  • 27
  • 1
    Look out for Builder pattern. – Rohit Jain Sep 26 '13 at 14:36
  • 3
    That's [fluent](http://en.wikipedia.org/wiki/Fluent_interface). They just inserted line breaks for clarity. – Tim S. Sep 26 '13 at 14:39
  • See [here](http://stackoverflow.com/questions/16976150/benefits-and-drawbacks-of-method-chaining-and-a-possibility-to-replace-all-void) for more information on method chaining and remember that whitespace largly has no meaning to the compiler. Imagine it all on one line – Richard Tingle Sep 26 '13 at 14:41

5 Answers5

13

This pattern is called method chaining.

Builder is a static inner class of AlertDialog.

Each method in Builder returns a Builder (usually "this") instead of void.

dkatzel
  • 31,188
  • 3
  • 63
  • 67
2

This means that Builder is a static nested class in AlertDialog class, that is

class AlertDialog {

   static class Builder {
..
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Builder is a static inner class of the AlertDialog class.

I advise you to read this about the use and the utility of nested classes

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
0

Check out the documentation!

Builder is a static class defined within the AlertDialog class. You are calling it's constructor.

Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
0

This is Builder design pattern.

What you do in your code:

  • Create instance of the Builder class - new AlertDialog.Builder(getActivity())
  • Set its properties calling setTitle and setPositiveButton
  • Create instance of AlertDialog by calling create() method with the properties of the Builder.

Builder pattern is a creational design pattern it means it solves problem related to object creation. Constructors in Java are used to create object and can take parameters required to create object. Problem starts when an Object can be created with lot of parameters, some of them may be mandatory and others may be optional. Builder Design pattern should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5.

Mario Kutlev
  • 4,897
  • 7
  • 44
  • 62