2.4.14 How to Define and Use Private Object Fields

Making fields that can be/are objects has a few nuances that are different from making value fields private. When you make an object field private no longer have access to anything that object is/does. You cannot even instantiate the field outside of its own class.

Let's say we want Employees to have their own time sheets. We can create a new class and give them a Timesheet object field.

Since the Timesheet is public we can instantiate it in the MainWindow and even force the Employee to punch out. This isn't good, however, because only the Employee should be able to punch in and out.

So let's make the Timesheet field private.

Now nothing can be done with the Employee's Timesheet outside of the Employee class.

See also: