Set and Get Methods vs. public Data

It would seem that providing set and get capabilities is essentially the same as making a class’s instance variables public. This is one of the subtleties that makes Java so desirable for software engineering. A public instance variable can be read or written by any method that has a reference to an object containing that variable. If an instance variable is declared private, a public get method certainly allows other methods to access it, but the get method can control how the client can access it. For example, a get method might control the format of the data it returns, shielding the client code from the actual data representation. A public set method can—and should—carefully scrutinize attempts to modify ...

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.