Why use getters and setters when we could make fields public?
Methods let a class validate input, compute values, log changes, and change its internal storage later without breaking callers. A public field gives up all of that control.
Explain it simply
A public field is like leaving your shop's cash drawer open on the street. A setter is the counter: people can still pay, but you check the amount first.
Methods also protect the future. If age is stored today and you later store dateOfBirth instead, a getAge() method can compute it and callers never notice.
Example
class Student {
private int marks;
public void setMarks(int marks) {
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("marks must be 0-100");
}
this.marks = marks;
}
public int getMarks() { return marks; }
}With public int marks, anyone could set 450 and the bug would show up far from the cause. A setter fails at the exact line that broke the rule.
Do not add setters automatically. A field that should never change after creation needs no setter at all.
What to say in the interview
"Accessors give one controlled place for validation, derived values and future changes to the internal representation. Public fields let any code break the object's invariants. I also avoid blind setters; immutable fields are better when possible."
Common mistakes
- Generating a getter and setter for every field. That is a public field with extra typing.