2.4.15 How to Instantiate Inside a Constructor

We saw earlier that if we make an object field private we cannot instantiate it from outside of the class. To fix this we will instantiate an object field within a constructor.

See also:


So we have a private field of type Timesheet..

...but it hasn't been instantiated anywhere. Assuming all Employees need a Timesheet, we can instantiate the Timesheet in the Employee constructor.

Now whenever a new Employee is instantiated, they will have their Timesheet instantiated at the same time.


We can see this at work by setting a breakpoint on an instantiation....

...pressing F11 to step into the constructor....

...and stepping over the instantiation of the new Timesheet.