Encapsulation: hiding state behind a boundary
Why public fields invite trouble, what access modifiers actually control, and when getters and setters are not enough.
Adetayo Akinsanya2026-08-045 min read
- Java
- Core Java
- OOP
- Encapsulation
- Access Modifiers

Part 10 of the series.Read Initialization order: when each line of code runs (Part 9) first if you have not.
In this article (7 sections)
public class Account {
public int balance;
}
Account a = new Account();
a.balance = -500;
The compiler accepts this. Nothing stops any caller from putting the account into a state the class was never designed to handle. Encapsulation is the practice of preventing exactly this.
What encapsulation protects
In Classes, fields, and constructors, we established that a constructor’s job is to put an object into a valid initial state. Encapsulation extends that idea to the whole lifetime of the object. A valid Account has a non-negative balance. If balance is public, any code anywhere in the program can violate that invariant directly. If it is private, only Account’s own methods can touch it, so the invariant is only as fragile as those methods.
The goal is not to hide data for its own sake. The goal is to make it impossible to violate an invariant without going through code that checks the invariant first.
The four access modifiers
Java has four access levels, controlled by the keyword you put before a field, method, or constructor declaration.
private: visible only within the declaring class. No other class, not even a subclass, can see it.
Package-private (no keyword): visible to all classes in the same package. This is the default when you write nothing.
protected: visible within the same package and to subclasses in any package.
public: visible everywhere.
public class Account {
private int balance; // only Account can read or write this
int transactionCount; // package-private: visible to Account and classes in its package
protected String ownerId; // visible to Account, its package, and subclasses
public String id; // visible everywhere
}
A good default for fields: private. Expose state only through methods that can enforce the invariants.
Methods as the controlled entry point
A private field with a public method gives the class control over every change to that field:
public class Account {
private int balance;
Account(String id, int initialBalance) {
if (initialBalance < 0) throw new IllegalArgumentException("balance cannot be negative");
this.balance = initialBalance;
}
public void deposit(int amount) {
if (amount <= 0) throw new IllegalArgumentException("deposit amount must be positive");
this.balance += amount;
}
public void withdraw(int amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
if (amount > this.balance) throw new IllegalStateException("insufficient funds");
this.balance -= amount;
}
public int getBalance() {
return this.balance;
}
}
Now every path that changes balance goes through a check. No external code can set the balance to -500. The class’s invariants hold as long as its methods are correct, and you only have to audit those methods, not every caller.
When getters and setters are not enough
A common mistake is to declare every field private and then generate a getter and setter for each one. That is not encapsulation. It is a private field with a public field hidden behind two method calls.
// this exposes balance exactly as much as a public field would
public void setBalance(int balance) {
this.balance = balance;
}
A setter with no logic is the same as a public field. The point of encapsulation is that the method enforces constraints. If setBalance does nothing but assign, any caller can still put the account into an invalid state.
Write methods that describe operations, deposit, withdraw, close, not methods that expose the internal slot. Sometimes a getter is appropriate for read access. A setter is appropriate only when unrestricted write access is genuinely part of the contract.
Immutable objects and records
The strongest encapsulation is immutability: a class whose state cannot change after construction. An immutable object can safely be shared across threads, used as a map key, and cached without coordination.
Before Java 16, writing an immutable value type required declaring all fields private final, writing a constructor that sets them, and providing only getter methods. Java 16 introduced records as a compact syntax for exactly this pattern.
public record Point(int x, int y) {}
The compiler generates:
- A constructor that takes
xandy - Private final fields
xandy - Accessor methods
x()andy()(notgetX()) equals(),hashCode(), andtoString()based on all components
Records cannot have mutable state. Their fields are always private final. You cannot add a setter. Use a record when the entire point of the class is to hold a fixed set of values, such as a coordinate, a range, or a result with a status and a value.
public record TransferResult(boolean success, String reason) {}
TransferResult result = new TransferResult(false, "insufficient funds");
System.out.println(result.success()); // false
System.out.println(result.reason()); // insufficient funds
Packages as a second boundary
The package-private level (no keyword) gives you a boundary that is wider than a single class but narrower than the whole program. Classes in the same package can share implementation details without exposing them to the rest of the codebase.
A common use: a public class with package-private helper classes. The helper classes are visible to the main class and to tests in the same package, but not to callers outside the package.
Packages are not a security boundary. Any code can be placed in any package. They are an organizational boundary that communicates intent and limits accidental coupling.
Prediction exercise
public class Counter {
private int count = 0;
public void increment() { count++; }
public void decrement() { count--; }
public int value() { return count; }
}
Can count ever go negative? If yes, what change would prevent it? If you converted Counter to a record, what would you lose and what would you gain?
Questions or corrections
Found a mistake or have a question about this breakdown? Reach out directly.