Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is encapsulation in Java beyond making fields private and adding getters and setters? Give an example where getters and setters still break it.

Encapsulation means a class is responsible for keeping its own state valid: callers can change it only through operations that preserve its rules, its invariants. Private fields are only the mechanism. A setter for every field still breaks encapsulation, because callers can put the object into an invalid state, for example by setting an account balance directly, and so does a getter that returns a mutable internal list.

Why this question is asked

Most of us learned encapsulation as 'make the fields private and generate getters and setters'. That habit produces classes that look encapsulated but protect nothing, and the bugs show up later as accounts with negative balances or orders whose total does not match their lines. Interviewers ask this question to see whether we understand the purpose behind the rule. In this answer, we will define an invariant, look at a class that has private fields and still breaks, find the two leaks, setters and mutable getters, fix them with intention-revealing methods and safe views, and end with immutability as the strongest form of encapsulation.

1A Quick Recap: What Encapsulation Protects

An invariant is a rule about an object's state that must always be true, from the moment it is constructed until it is thrown away. For a bank account, the balance is never negative. For an order, the total equals the sum of its lines. Encapsulation is the practice of putting that state and the code that changes it in one class, and allowing changes only through methods that keep the invariants true.

Private fields are how Java helps: no other class can touch them directly. But a private field is only private if every way out of the class respects the rules too. Public methods are the doors, and each door can either check the rules or let anything through.

2Private Fields That Protect Nothing

Here is an account generated in the usual way. Every field is private, and every field has a getter and a setter.

Java
class Account {
private long balanceCents;
private final List<String> history = new ArrayList<>();
public long getBalanceCents() { return balanceCents; }
public void setBalanceCents(long b) { this.balanceCents = b; }
public List<String> getHistory() { return history; }
}
Account acc = new Account();
acc.setBalanceCents(-50_000); // accepted: the balance is now -500.00
acc.getHistory().add("deposit 1000"); // a fake history entry, the account never knew
acc.getHistory().clear(); // the audit trail is gone

Nothing in this class can enforce the rule 'balance is never negative', because setBalanceCents accepts any number from anyone. The rule now lives, if anywhere, in every caller that remembers to check before calling the setter. The getter leaks in a different way: it returns the reference to the internal ArrayList, so callers can add or clear entries without going through the account at all. The fields are private, yet the state is completely public.

3Fix 1: Methods That Say What Happens

The fix is to replace data-shaped methods with intention-revealing ones, methods named after the business operation they perform. Instead of setBalance, the account offers deposit and withdraw, and each one checks the rules and updates all related state together.

Java
class Account {
private long balanceCents;
private final List<String> history = new ArrayList<>();
public void deposit(long cents) {
if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
balanceCents += cents;
history.add("deposit " + cents);
}
public void withdraw(long cents) {
if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
if (cents > balanceCents) throw new IllegalStateException("insufficient funds");
balanceCents -= cents;
history.add("withdraw " + cents);
}
public long balanceCents() { return balanceCents; }
}
Account acc = new Account();
acc.deposit(10_000); // balance 10000
acc.withdraw(30_000); // IllegalStateException: insufficient funds, balance still 10000

Notice what changed. There is no longer any way to set the balance to an arbitrary value, so the invariant is checked in exactly two places, both inside the class. The history and the balance are updated in the same method, so they can never disagree. And callers read better: acc.withdraw(30_000) says what the code means, while acc.setBalanceCents(acc.getBalanceCents() - 30_000) makes every reader work it out.

4Fix 2: Do Not Hand Out Mutable Internals

The history still needs to be readable. We return it in a form that cannot be used to change the account.

Java
public List<String> history() {
return Collections.unmodifiableList(history); // read-only view of our list
}
acc.history().add("fake"); // UnsupportedOperationException
acc.history().size(); // 2: reading is fine
Getters and setters versus encapsulated operations
Caller wants toLeaky APIEncapsulated API
take money outsetBalance(getBalance() - x)withdraw(x), checks funds
put money insetBalance(getBalance() + x)deposit(x), rejects zero or less
read the historygetHistory() returns the real listhistory() returns a read-only view
reset the balancesetBalance(0), allowednot offered at all
The encapsulated API exposes operations, not fields.

Collections.unmodifiableList returns a cheap read-only view: callers can read it, and they see later changes, but any attempt to modify it throws. If callers might keep the list for a long time or use it from another thread, List.copyOf(history) returns an immutable snapshot instead. Either way, the only way to add a history entry is to deposit or withdraw, which is exactly what we want.

5Immutability: The Strongest Form

The safest state is state that never changes. An immutable object sets all its fields in the constructor, checks the invariants once there, and offers no method that changes them afterwards. There is nothing left to protect, so it can be shared freely between callers and threads. Java records make this short to write.

Java
record Money(long cents, String currency) {
Money {
if (cents < 0) throw new IllegalArgumentException("negative amount");
Objects.requireNonNull(currency);
}
Money plus(Money other) { return new Money(cents + other.cents, currency); } // a new object
}
Money a = new Money(500, "EUR");
Money b = a.plus(new Money(250, "EUR"));
System.out.println(a.cents() + " " + b.cents()); // 500 750

Notice that plus does not change a; it returns a new Money. Not every object can be immutable, an account's balance must change over time, but value objects such as amounts, addresses and date ranges usually can, and every one we make immutable is one less place where an invariant can break.

6Follow-up questions

Are getters always a problem?

No. A getter that returns an immutable value, such as a long, a String or a record, exposes information without giving control, and that is often exactly what callers need. The problems are setters that allow any value, and getters that return mutable objects owned by the class. The question to ask for each public method is whether a caller could use it to break a rule the class is supposed to guarantee.

Do frameworks force us to add setters?

Less than they used to. Jackson can bind JSON through constructors and records, JPA can access fields directly, and Spring can inject through constructors. Where a framework really needs a setter, it can often be package-private or protected, and API data transfer objects can be kept separate from domain objects so the domain class does not have to be shaped for the framework.

How does encapsulation relate to the 'tell, don't ask' advice?

They point in the same direction. Asking an object for its data and deciding outside it, as in reading the balance and then setting a new one, spreads the rules across callers. Telling the object what to do, as in withdraw, keeps the decision and the rule inside the class that owns the data.

7Conclusion

In this answer, we saw that encapsulation is about a class protecting its invariants, not about the private keyword alone. A setter for every field let callers set a negative balance, and a getter that returned the internal list let them rewrite the history. We fixed both with intention-revealing operations such as deposit and withdraw that check the rules and update related state together, returned an unmodifiable view or a copy instead of the internal list, and saw that immutable value types are the strongest form of encapsulation because there is no state change to control.

What to say in the interviewAbout 80 seconds aloud

Open with

Encapsulation is not really about private fields; private fields are just the tool. The idea is that a class owns its state and its invariants, the rules that must always hold, and callers can only change that state through operations that keep those rules true.

Then, if they want more

A class with private fields and a public setter for each one does not achieve that. For example, an Account with setBalance lets any caller set the balance to minus five hundred, so the rule that the balance is never negative cannot be enforced anywhere.

A getter that returns the internal history list is another leak, because callers can add fake entries or clear it without the account knowing. So I design the API around intention: deposit and withdraw, which validate the amount, check funds and update the balance and the history together, and no setBalance at all.

For collections I return Collections.unmodifiableList, or List.copyOf when the caller may keep it. And where possible I make value objects immutable, for example a Money record that validates in its constructor and returns a new object from plus. Immutability is the strongest form of encapsulation, because after construction there is no state change left to control.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is encapsulation in Java beyond making fields private and adding getters and...": https://scrivio-interview-library.netlify.app/java/oop-principles/c4bd61de11/