3.2.6 Software Engineering with private Instance Variables and public set and get Methods

As you’ll see, through the use of set and get methods, you can validate attempted modifications to private data and control how that data is presented to the caller—these are compelling software engineering benefits. We’ll discuss this in more detail in Section 3.5.

If the instance variable were public, any client of the class—that is, any other class that calls the class’s methods—could see the data and do whatever it wanted with it, including setting it to an invalid value.

You might think that even though a client of the class cannot directly access a private instance variable, the client can do whatever it wants with the variable through public set ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.