Search code examples
javaclassinstantiation

Why is there no "new" keyword in this example of instantiating a class?


I am learning Java. To instantiate a class we use the new keyword, but I don't understand what this line of code means. Why there is no new keyword here?

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
                                      AppDatabase.class,
                                      "database_transaction").build();

Solution

  • You ask about this:

    AppDatabase db = Room.databaseBuilder(getApplicationContext(),
                                          ppDatabase.class,
                                          "database_transaction").build();
    

    This is a call to a method (the static method databaseBuilder on a Room class) followed by a second call to a build() method on the object returned by the first call. The second call is then returning an AppDatabase object.

    Somewhere inside one of those methods, I expect that new is being used to explicitly create a new object1.

    This looks like an example of a general pattern called the Factory Method pattern where the logic of creating objects is encapsulated in a static method or an instance method. More specifically, this looks like the Builder pattern.

    It is worth reading those two links to understand the advantages and drawbacks of those patterns. They can also be combined with the Fluent Interface API design pattern to reduce the number of parameters and/or method overloads.


    1 - I could be wrong. It is possible to create objects in other ways; e.g. by boxing, by deserializing an object serialization stream or by using Unsafe or native code methods. It is also possible that the names of the methods are misleading and build() is returning a pre-existing object.