3.1.10 How to Use Inline Instantiation

Much like inline method calls, instantiating an object can be shortened as well. This is done in places where you do not need to use the object again in any other context or need a reference to. Most commonly it is used when instantiating objects when they are being passed to a constructor.


Let's take a look at the two lines below. The first line instantiates an Employee and stores that Employee in a local variable. The second line instantiates a Restroom and passes in the custodian variable as an argument to the constructor.

We can combine these two lines of code by moving the instantiation of the custodian to directly inside the constructor like this:

Remember, however, that doing this...

...is not the same as passing in the same object as the mensRoom. If you want to pass the same object into several constructors you need to assign it to a local variable.