Interview Q&A / Object-Oriented Programming

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Why use getters and setters when we could make fields public?

SHORT ANSWER

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

java
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.

#encapsulation#getters-setters#java

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.