What is the point of setters and getters in java? [duplicate]

The point of getters and setters, regardless of language, is to hide the underlying variable. This allows you to add verification logic when attempting to set a value – for example, if you had a field for a birth date, you might only want to allow setting that field to some time in the past. This cannot be enforced if the field is publicly accessible and modifyable – you need the getters and setters.

Even if you don’t need any verification yet, you might need it in the future. Writing the getters and setters now means the interface is kept consistent, so existing code won’t break when you change it.

Leave a Comment