Lesson · Classes and Objects
Encapsulation: private state, public promises
18 min readEncapsulation
Private fields are only the beginning. The real contract is invariants enforced through methods, defensive copies in both directions, and accessors that describe operations instead of leaking storage.
The broken object
Start where it hurts. A bank account modelled with a public field, and one line from any caller:
class Account { public long balanceCents; } Account account = new Account(); account.balanceCents = -500; // invalid state, zero resistance
- Every reader becomes a debugger: each method that touches the balance would have to re-check for impossible values, forever.
- No single place to fix: the rule 'balance never negative' lives in no method, so it is enforced nowhere.
- The class cannot evolve: switching to dollars, to cents plus currency, or to any other representation would ripple out to every caller that wrote to the field.
Did private fields solve this, or did the operation? Make a prediction before reading on. The next two sections separate the two: the modifier removes the assignment, and the method's validation is what keeps the object legal.
Access control
The first fix is a removal: hide the storage, and expose an operation that owns the rules.
class Account { private long balanceCents; // storage: gone from the public surface void deposit(long cents) { // operation: owns the rules if (cents <= 0) { throw new IllegalArgumentException("Deposit must be positive"); } balanceCents += cents; } }
| Modifier | Same class | Same package | Subclass | Everywhere |
|---|---|---|---|---|
| private | Yes | No | No | No |
| package-private (default) | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |
Private removed the assignment; the operation's validation is what keeps the balance legal. Access control hides names, behaviour guards state. Two fine points on the table: the default modifier is package-private, not private, and protected is not unrestricted subclass access. In a different package, a subclass reaches inherited protected instance members through itself or a compatible subclass reference, not through an arbitrary superclass instance.
Invariants and operations
Access control removes the wrong door; operations are the right one. The useful version of a class exposes behaviour, and each behaviour answers for the whole object:
| Member | Responsibility |
|---|---|
deposit(cents) | Validates the operation, then applies it. Illegal attempts die at the door. |
balanceCents() | Exposes a read-only fact; nothing about the storage leaks through it. |
balanceCents field | Inaccessible to callers, and free to change representation later. |
deposit(cents)validates its input, applies the account's rule, and updates the balance.setBalanceCents(anything)would accept every value, so the invariant would depend on caller discipline instead.- A bug through the setter becomes every caller's fault forever; through
depositit stays inside one method that can be fixed once.
- Teaching note: this example demonstrates encapsulation. A production banking account would add withdrawal rules, currency precision, and possibly concurrency control on top; the shape is the lesson here.
Expose operations, not storage. Getters for genuinely read-only facts are fine; a setter earns its place only when arbitrary assignment is itself a meaningful operation, which is rarer than generated code suggests.
Reference escape
A private field can still leak, because privacy protects the name and not the object. Watch a getter hand the internal state straight to the caller:
private final Date openedAt; Date openedAt() { return openedAt; // hands out the INTERNAL object } Date d = account.openedAt(); d.setTime(0); // account state changes: 1970
A private field with a leaky getter is public state with extra syntax. No modifier was violated and the compiler saw nothing; the reference escaped, and anything reachable through it is public in practice. The playground below runs this attack and the copy that stops it.
Reference escape playground
1 / 3private final Date openedAt;
Date openedAt() {
return openedAt; // returns the INTERNAL object
}
Date d = account.openedAt(); // caller receives it
d.setTime(0); // mutates account state
Expected: the account's openedAt changes, even though the field is private.
Reference flow
Verdict
Awaiting execution
No caller holds a reference yet. Step forward to hand one out.
The account exists with its private Date. Nothing outside the class can reach it yet.
Defensive copying, and its alternatives
Copy on the way out protects reads; copy on the way in protects construction. Both directions matter, and copying is one strategy among several:
- Immutable types:
Instant,LocalDate,String. No copy needed, because there is nothing to mutate. - Unmodifiable views:
Collections.unmodifiableListhides the mutators, but it does not freeze the underlying list: keep the only mutable reference to yourself. - Ownership transfer: document that ownership moves with the handover: the receiving code now owns the object, and the caller will not touch it again.
- Deliberate sharing: an explicitly documented, synchronised shared object. That is a contract, not an accident.
Never retain or expose an uncontrolled shared reference. If your class must control the state of a mutable object, copy it, switch to an immutable representation, or define a clear ownership and mutation contract. The rule is about control, not about copying for its own sake.
Immutable objects
The strongest encapsulation is a class that simply cannot change. Choosing immutable types removes the copying entirely, which the modern version shows:
import java.time.Instant; public final class Account { private final Instant openedAt; public Account(Instant openedAt) { this.openedAt = Objects.requireNonNull(openedAt); } public Instant openedAt() { return openedAt; // no copy: Instant is immutable } }
- Make the class
finalwhere possible, so no subclass can add mutation paths. A class can be immutable without final if subclassing cannot introduce observable change, but final is the pragmatic choice. - Make every field
private final. - Initialise and validate all state in the constructor.
- Copy every mutable argument in; copy, wrap, or replace with an immutable type on the way out.
A properly constructed immutable object can be shared across threads without synchronisation for its own state, and works as a map key while equals and hashCode are based on stable state. The qualifications matter: the guarantee extends only as far as the reachable object graph, and only once the reference is safely published. One mutable object behind a final field, or a reference published unsafely, reopens the whole question.
Review and practice: the encapsulation playbook
Apply the whole lesson to an unfamiliar class, in the order that finds the real problems:
- List every public method and ask: can any of them put the object into a state the others do not expect?
- Check every mutable field: is there a copy on the way in, a copy on the way out, an immutable type, or a documented reason none is needed?
- Find every accessor pair with no logic: each is a candidate for deletion or for becoming an operation (
deposit,addItem,apply). - Audit thread-safety claims: immutable objects need none for their own state, and mutable ones need a plan.
Encapsulation is judged by what callers cannot do, not by how many private keywords the file contains. Unreachable bad states are the metric.
The getter that leaks the whole array
A private int[] with a public getter is a public array. The caller receives the internal reference, writes values[0] = 99, and your invariant is gone with zero compiler help. Return a copy, an immutable type, or a documented read-only contract, and give every mutable object you accept the same treatment on the way in.
Interview angles
Is a getter and setter pair considered encapsulation?+
No. It exposes storage in different syntax. Access control hides names; encapsulation is about enforcing invariants, and a blind setter accepts every value.
Encapsulation is the set of operations that keep the object legal. deposit() validates its input and owns the rule; setBalance() would have to trust every caller forever. The modifier changes who can see the field; the method is what keeps the object correct. Those are two different jobs, and only the second one is encapsulation.
class Account { private long balanceCents; void deposit(long cents) { // operation: validates if (cents <= 0) throw new IllegalArgumentException(); balanceCents += cents; } }
Common misconception: That private fields plus generated getters and setters are the definition of encapsulation. That is only the syntax. The test is behavioural: can any caller still put the object into a state your methods do not expect?
Follow-up: So what would you expose instead of a setter for a field that legitimately changes?
What is a defensive copy, and when are copies needed in both directions?+
A copy taken to stop shared mutable state: copy in when the constructor stores a mutable argument the caller still holds, and copy out when a getter would otherwise return an internal mutable field.
Each direction protects a different moment. Copy in protects construction: the caller keeps their reference and cannot mutate your state through it. Copy out protects reads: the caller can mutate what they were handed without touching the account. Either direction left uncopied is a live wire into the object. Copying is also only one strategy: immutable types, unmodifiable views, or a documented ownership contract can remove the need entirely.
Account(Date openedAt) { this.openedAt = new Date(openedAt.getTime()); // copy IN } Date openedAt() { return new Date(openedAt.getTime()); // copy OUT }
Common misconception: That privacy of the field is privacy of the state. A private mutable field with a getter that returns it is still public state, just spelled differently.
Follow-up: What is the modern alternative to copying Dates around?
Can a private field still leak?+
Yes, whenever a reference to the field's object escapes the class: returning it from a getter, storing a caller's object directly, or handing it to a collaborator that keeps it.
The field was never the state; the object it points at is. Privacy is a property of names, sharing is a property of references, and only the second one can be violated without the compiler noticing. Every mutable type is a candidate: arrays, collections, Date, and any custom class with mutators.
int[] values() { return values; } // hands over the internal array // caller: returned[0] = 99; // writes straight into your state
Common misconception: That encapsulation is achieved by making fields private. It is achieved by keeping control of every reference that crosses the boundary.
Follow-up: Name the places where a copy or an immutable type removes the leak entirely.
Does immutable always mean thread-safe?+
Not automatically. A properly constructed immutable object is safe to share without synchronisation for its own state, but the guarantee holds only across its reachable object graph and only with safe publication.
Three qualifications. A mutable object reachable through a field (a final Date, an array) breaks immutability, because the object graph is part of the object. An unsafely published reference can expose partially constructed state even with final fields in place. And a class can be immutable without being final if subclassing cannot introduce observable change, though final is the pragmatic choice. As a map key, the guarantee holds while equals and hashCode are based on stable state.
final class Period { private final Date start; // final field... Period(Date start) { this.start = start; } // ...but still mutable! } // start.setTime(0) changes this object's state after construction
Common misconception: That final fields and a missing setter are enough for thread safety. The object graph and how the reference was published matter just as much.
Follow-up: How can a subclass break an otherwise encapsulated class?
How can a subclass break encapsulation?+
By overriding a method the parent's own invariants depend on, or by depending on protected members the parent never designed as a contract.
The classic case is calling an overridable method from a constructor: the subclass's override runs before the subclass's fields are initialised. Protected access is also narrower than people assume: in a different package, a subclass reaches inherited protected instance members through itself or a compatible subclass reference, not through an arbitrary superclass instance. The design responses are final classes, private or static helper methods called from constructors, and composition over inheritance where possible.
class Parent { Parent() { init(); } // calls an overridable method void init() { } } class Child extends Parent { int value = 42; @Override void init() { System.out.println(value); // runs BEFORE value is assigned: prints 0 } }
Common misconception: That protected means 'public to subclasses'. In another package it is deliberately narrower, and it still exposes implementation detail to every future subclass forever.
Follow-up: How would you redesign the parent so the bug in that code becomes impossible?