- Prerequisites
- 4.1 Classes · 4.2 Objects
- Covers
- Information hiding · Access control · public · protected · package-private · private
- Related
- 5.2 Abstraction · 5.3 Encapsulation vs Abstraction · B1V5 Ch1 Java Modules · Book 5 Vol I (modularity, information hiding)
On this page
1Concept / Definition
Encapsulation means keeping an object's state and implementation inside it, and allowing the outside world to interact only through a controlled set of operations. It has two parts: bundling data with the behaviour that operates on it, and restricting access so that other code cannot read or change the internals directly.
The purpose is not secrecy for its own sake. It is to make one class responsible for keeping its data valid, and to leave that class free to change its internals without breaking anyone else.

2Why It Exists
Without encapsulation, every piece of code that touches an object's fields must know and enforce its rules. Rules get duplicated, then inconsistent, and invalid data appears in production — negative balances, orders shipped without payment. Changing a field's type or meaning then requires finding every place that uses it.
David Parnas described the principle in 1972 as information hiding: modules should hide the design decisions most likely to change. Java's access modifiers, packages and modules are the language tools for doing that.
3Core Concepts
Information hiding
Information hiding is the design principle; access modifiers are its enforcement. The principle asks: which decisions in this class are likely to change? — the data structure, the algorithm, the storage format, a third-party library. Those decisions should be invisible to callers, who depend only on the stable part: method names, parameters, documented behaviour.

A common misconception is that private fields with a getter and setter for each are encapsulated. They are not: the design decision ("there is a balance field of type BigDecimal that anyone may set") is fully exposed. True encapsulation exposes behaviour — deposit, withdraw — and hides the representation.
Access control
Java controls visibility at four levels for class members, and two for top-level classes (public or package-private). The rule of thumb is to give every member the narrowest access that works, and widen it only with a reason.

public
Visible to any class that can see the containing class. Public members form the class's API and are a long-term commitment: once other code depends on them, changing them is a breaking change. In a modular application (Java Platform Module System), public types are visible outside the module only if their package is exported.
protected
Visible within the same package and to subclasses in other packages (through inheritance). protected is an API for subclasses and should be treated as public in terms of compatibility, because any subclass anywhere may depend on it. It is often overused for fields; protected fields break encapsulation for every subclass.
package-private
The default when no modifier is written: visible only within the same package. It is the most underused level. Grouping a feature's classes in one package and keeping everything package-private except a small public façade gives a clear boundary without modules.

private
Visible only within the top-level class that declares it (including its nested classes). All fields should normally be private. Private methods hold implementation steps; private constructors prevent instantiation (utility classes) or force the use of factories.

4How It Works Internally
Access control is checked by the compiler and again by the JVM during linking: bytecode that tries to access a private member of another class fails with IllegalAccessError. Since Java 11, nested classes and their enclosing class are nestmates and can access each other's private members directly, without the synthetic accessor methods older compilers generated.
Reflection can bypass ordinary access checks with setAccessible(true), which frameworks use for dependency injection and persistence. Since Java 16–17, strong encapsulation of JDK internals prevents this for JDK packages unless explicitly opened with --add-opens, and modules can refuse reflective access to their own packages unless they open them.

Figure 6 puts the checks in order. Most violations never get past javac. Bytecode produced some other way is checked again when the JVM links it, so a private member cannot be reached by editing a class file either. Reflection is the one deliberate gap, and the module system narrows it: inside your own code setAccessible(true) still works, while the JDK's own packages stay closed unless a command-line option opens them (Example 6).
5APIs / Features / Syntax
| Tool | Encapsulation it provides |
|---|---|
| private final fields | State cannot be accessed or replaced from outside |
| Package-private classes | Implementation types invisible outside the package |
| Unmodifiable views / copies (List.copyOf) | Internal collections cannot be changed by callers |
| Records | Immutable, encapsulated data; accessors only |
| Sealed classes and interfaces | Only permitted subclasses can extend a type |
| module-info.java exports / opens | Only exported packages are visible to other modules |
6Practical Examples
Example 1 — From exposed to encapsulated
// Before: data holder, rules live in every caller
public class Account {
public BigDecimal balance;
public boolean frozen;
}
// After: behaviour guards the invariant balance >= 0
public class Account {
private BigDecimal balance = BigDecimal.ZERO;
private boolean frozen;
public void deposit(BigDecimal amount) {
requirePositive(amount);
requireActive();
balance = balance.add(amount);
}
public void withdraw(BigDecimal amount) {
requirePositive(amount);
requireActive();
if (balance.compareTo(amount) < 0) {
throw new InsufficientFundsException(balance, amount);
}
balance = balance.subtract(amount);
}
// read-only; BigDecimal is immutable
public BigDecimal balance() { return balance; }
public void freeze() { frozen = true; }
private void requireActive() {
if (frozen) throw new IllegalStateException("account frozen");
}
private static void requirePositive(BigDecimal amount) {
if (amount.signum() <= 0) throw new IllegalArgumentException("amount must be > 0");
}
}
Example 2 — Mini program: three ways private state leaks, and the fix
Problem. Example 1 makes the fields private, but private fields alone do not stop state from escaping. This program shows the usual leaks, a constructor that keeps the caller's list and array and a getter that hands out the internal list, next to a class that copies on the way in and on the way out.
public class LeakDemo {
static final class LeakyRoster { // three leaks
private final List<String> names;
private final int[] scores;
LeakyRoster(List<String> names, int[] scores) {
this.names = names; // 1. keeps the caller's list
this.scores = scores; // 2. and the caller's array
}
List<String> names() { return names; } // 3. hands out its own list
@Override public String toString() {
return names + " " + Arrays.toString(scores);
}
}
static final class Roster { // copy in, read-only out
private final List<String> names;
private final int[] scores;
Roster(List<String> names, int[] scores) {
if (names.size() != scores.length)
throw new IllegalArgumentException("sizes differ");
this.names = List.copyOf(names);
this.scores = scores.clone();
}
List<String> names() { return names; } // unmodifiable already
int[] scores() { return scores.clone(); } // arrays: copy out too
int total() { return Arrays.stream(scores).sum(); }
@Override public String toString() {
return names + " " + Arrays.toString(scores);
}
}
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("asha", "ravi"));
int[] scores = {70, 80};
LeakyRoster leaky = new LeakyRoster(names, scores);
Roster safe = new Roster(names, scores);
scores[0] = -999; // the caller changes its own array
leaky.names().clear(); // a reader changes what it was given
safe.scores()[1] = 0; // ... and tries the same on the copy
System.out.println("leaky: " + leaky);
System.out.println("safe: " + safe + ", total " + safe.total());
System.out.println("caller: " + names + " (cleared through leaky)");
try {
safe.names().add("intruder");
} catch (UnsupportedOperationException e) {
System.out.println("safe.names() is read-only");
}
}
}leaky: [] [-999, 80]
safe: [asha, ravi] [70, 80], total 150
caller: [] (cleared through leaky)
safe.names() is read-only
Why it behaves this way. LeakyRoster stores the references it was given, so it shares its list and its array with the caller: setting scores[0] in main changes the roster, and leaky.names().clear() empties both the roster's list and the caller's own, because they are one object. Roster copies both in its constructor. List.copyOf also returns an unmodifiable list, so names() can hand it out directly, while the array has to be copied again on the way out, because an array cannot be made read-only. The size check in the constructor is only worth something because of the copies: without them a caller could break the rule straight afterwards (Figure 8).
Example 3 — Hiding the representation
public class Cart {
// hidden choice
private final Map<String, Integer> quantities = new HashMap<>();
public void add(String sku, int qty) {
quantities.merge(sku, qty, Integer::sum);
}
public Map<String, Integer> items() {
return Map.copyOf(quantities); // callers cannot modify internal state
}
}
// Switching to a List<Line> or a sorted TreeMap later changes no caller.Example 4 — Package as a boundary
// com/shop/payment/PaymentService.java
public class PaymentService { // the only public type
private final CardGateway gateway = new CardGateway();
private final FraudRules fraud = new FraudRules();
public Receipt pay(Order order, Card card) { … }
}
// com/shop/payment/CardGateway.java
class CardGateway { … } // package-private: invisible outside
// com/shop/payment/FraudRules.java
class FraudRules { … } // package-privateExample 5 — The package boundary, checked by the compiler
Problem. Example 4 keeps CardGateway and FraudRules package-private so that only PaymentService is visible outside com.shop.payment. This is what happens when code in another package tries to use the hidden class anyway.
import com.shop.payment.PaymentService;
import com.shop.payment.CardGateway; // not public in its package
public class Checkout {
public String run() {
new CardGateway().charge(49_900); // bypass the facade
return new PaymentService().pay(49_900);
}
}Compiled together with small versions of the payment classes (the two long error lines are wrapped here):
$ javac -d out com/shop/payment/*.java com/shop/checkout/Checkout.java
com/shop/checkout/Checkout.java:6: error: CardGateway is not public in
com.shop.payment; cannot be accessed from outside package
import com.shop.payment.CardGateway; // not public in its package
^
com/shop/checkout/Checkout.java:10: error: CardGateway is not public in
com.shop.payment; cannot be accessed from outside package
new CardGateway().charge(49_900); // bypass the facade
^
2 errorsWhy it behaves this way. A top-level class without public is visible only inside its package, so javac rejects the import and the use. The boundary holds without a module system, an architecture test or a code review: nothing outside the package can even name CardGateway. The error appears in the other team's build, the cheapest place to learn that a class is not part of the API. To use payment, the checkout code must go through PaymentService, where the fraud rules are applied.
Example 6 — Reflection, setAccessible and strong encapsulation
Problem. Section 4 says that reflection can bypass access control in your own code but not in the JDK. This program tries both.
class Wallet { // a separate top-level class
private long balance = 100; // invariant: never negative
}
public class ReflectionDemo {
public static void main(String[] args) throws Exception {
Wallet w = new Wallet();
Field f = Wallet.class.getDeclaredField("balance");
try {
f.getLong(w);
} catch (IllegalAccessException e) {
System.out.println("plain reflection: IllegalAccessException");
}
f.setAccessible(true); // allowed: same module
f.setLong(w, -5);
System.out.println("after setAccessible: balance = " + f.getLong(w));
Field value = String.class.getDeclaredField("value");
try {
value.setAccessible(true); // java.base does not open it
} catch (InaccessibleObjectException e) {
System.out.println("JDK internals: "
+ e.getClass().getSimpleName());
}
}
}plain reflection: IllegalAccessException
after setAccessible: balance = -5
JDK internals: InaccessibleObjectExceptionWhy it behaves this way. Field.getLong makes the same access check as the compiler, so reading a private field of another class fails with IllegalAccessException. setAccessible(true) switches the check off for that Field, which is allowed because Wallet is in the caller's own module, here the unnamed one; the program then sets the balance to -5, which no method of Wallet would allow. That is the power frameworks use for injection and persistence, and the reason it belongs only in frameworks. For String.value the same call throws InaccessibleObjectException: java.base does not open java.lang, and since Java 17 only an explicit --add-opens java.base/java.lang=ALL-UNNAMED changes that. Wallet is a separate top-level class on purpose: a nested class would be a nestmate of ReflectionDemo, and even the first read would succeed.
7Common Problems & Mistakes
| Mistake | Why it breaks encapsulation | Better approach |
|---|---|---|
| Getter and setter for every field | Representation fully exposed; rules still in callers | Expose behaviour; add getters only where needed, setters rarely |
| Returning internal mutable collections | Callers modify state without checks | List.copyOf, unmodifiable views, or iteration methods |
| Storing caller's mutable objects directly | Caller can change internal state later | Defensive copy in constructor/setter |
| protected fields for subclasses | Every subclass anywhere depends on the representation | private fields with protected methods if needed |
| Everything public "for testing" | Implementation becomes de facto API | Test through the public API; package-private for test access in same package |
| Leaking this or internals in toString/logging | Sensitive data exposed | Choose what toString shows; never include secrets |
| Records with mutable components | The fields are final, but a List or array inside can still change, so the "immutable" value is not | Copy in the compact constructor: List.copyOf, array clone() (Q12) |
| setAccessible on another library's private fields | The code depends on internals that may change in any release; JDK internals are blocked since Java 16-17 | Use the public API or ask for an extension point; keep --add-opens out of application code |
8Performance & Production Considerations
- Accessor methods cost nothing after JIT inlining; there is no performance reason to make fields public.
- Defensive copies do cost allocation. For large collections, return unmodifiable views, or expose iteration or stream methods, instead of copying on every call.
- Encapsulated invariants reduce data-corruption incidents, which are among the most expensive production failures to diagnose and repair.
- Every
--add-opensis a dependency on JDK internals. Keep them in one place, the launcher script or theAdd-Opensentry of an executable JAR's manifest, record which library needs each one, and re-check the list on every JDK upgrade; most disappear when the library is upgraded.
9Architecture & Design Considerations
Encapsulation scales from classes to systems:
| Level | Boundary | Encapsulation mechanism |
|---|---|---|
| Class | Object state | private fields, behaviour methods |
| Package | Feature or component | package-private classes, one public façade |
| Module | Library or bounded context | module-info exports; ArchUnit rules |
| Service | Microservice | Own database, API as the only access path |
10Interview Questions & Answers
What is encapsulation?
Bundling data with the methods that operate on it and restricting direct access to that data, so that the object controls how its state changes and can keep it valid.
What are Java's access modifiers and their scopes?
private: the top-level class that contains the declaration, its nested classes included. Package-private (no modifier): the same package. protected: the same package plus subclasses in other packages. public: everywhere the class is visible (and, with modules, outside the module only if the package is exported).
Is a class with private fields and public getters and setters for all of them encapsulated?
Only nominally. The fields are private, but the representation and all mutation are exposed, and validation rules must be enforced by callers. Real encapsulation exposes meaningful behaviour and keeps the representation and its rules inside the class.
What is the difference between encapsulation and information hiding?
Information hiding is the design principle of hiding decisions that are likely to change behind a stable interface. Encapsulation is the mechanism of bundling state with behaviour and restricting access. Encapsulation is how Java code achieves information hiding.
Why is returning an internal List from a getter a problem, and how do you fix it?
The caller receives a reference to the internal list and can add or remove elements without any of the class's checks. Return List.copyOf, an unmodifiable view, or provide specific methods, and copy mutable inputs in constructors. Example 2 shows the leak and the fix.
When would you use package-private access deliberately?
For implementation classes and methods within a feature package that other packages should not use — gateways, mappers, rule classes — leaving a small public façade. It also allows tests in the same package to access helpers without making them public.
Why are protected fields considered harmful?
Any subclass, in any package, can read and write them, so the superclass can no longer change its representation or guarantee its invariants. The superclass effectively has as many uncontrolled clients as it has subclasses. Private fields with protected methods, or composition, keep control.
Can reflection break encapsulation, and what has Java done about it?
Yes: setAccessible(true) bypasses access checks, which frameworks rely on. Since Java 16–17, JDK internals are strongly encapsulated and cannot be accessed reflectively without --add-opens, and modules must explicitly open packages to allow deep reflection. Application code should not rely on reflective access to private members. Example 6 shows both cases.
How do you enforce encapsulation boundaries in a large monolith?
Organise by feature packages with package-private internals and one public API per package; move to JPMS modules or build modules where appropriate; enforce dependency rules with architecture tests such as ArchUnit in CI; and forbid cross-module database access. This keeps a modular monolith modular over time.
How does encapsulation relate to microservice data ownership?
It is the same principle at a larger scale: each service owns its data and exposes it only through its API, just as an object owns its fields and exposes behaviour. Sharing a database between services is equivalent to public fields — every consumer depends on the schema, and it cannot change safely.
A team argues that encapsulation slows them down and wants public fields in DTOs and entities. How do you respond?
Separate the cases. Pure data carriers crossing boundaries can be records — immutable, no behaviour — which is fine and fast. Domain entities with business rules should keep state private and expose behaviour, because the cost of scattered rules and invalid data in production outweighs the saved lines of code. Agree the rule per layer and enforce it with static analysis rather than debating each class.
What does this program print?
public class RecordQuiz {
record Team(String name, List<String> members) {}
public static void main(String[] args) {
List<String> members = new ArrayList<>(List.of("asha"));
Team team = new Team("core", members);
members.add("ravi");
System.out.println(team.members().size() + " " + team);
}
}It prints 2 Team[name=core, members=[asha, ravi]]. A record's components are final, but final fixes only the reference: team.members() returns the same ArrayList the caller passed in, so the caller's later add shows up in the record. The record is only shallowly immutable. A compact constructor, Team { members = List.copyOf(members); }, makes it deeply immutable, and members().add(...) then throws UnsupportedOperationException.
How can a nested class read its enclosing class's private fields, and what changed in Java 11?
The JVM checks private access per class, and a nested class is a separate class file (4.1). Before Java 11, javac made the access legal by generating synthetic package-private accessor methods, such as access$000, in the enclosing class; at bytecode level that widened the private member to the whole package and added extra frames to stack traces. Since Java 11 (JEP 181) the classes of one top-level declaration form a nest, recorded in the NestHost and NestMembers attributes, and the JVM allows private access between nestmates directly. Reflection follows the same rule.
JPA and Jackson seem to want a no-argument constructor and setters for every field. How do you keep entities encapsulated?
Let the frameworks use fields rather than properties: JPA reads and writes fields directly when the @Id is on a field, and Jackson can use fields or a constructor marked with @JsonCreator, so public setters are not needed. Make the no-argument constructor protected, keep behaviour methods as the only way to change state, and validate in them. If the mapping still gets in the way, separate the persistence or API model from the domain model and map between them, at the cost of a mapping layer. Decide per layer: API payloads can be plain records, while entities with business rules should not have public setters.
Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Encapsulation = state + behaviour together, with access restricted.
- Information hiding: hide the decisions likely to change; callers depend only on the contract.
- Narrowest access that works: private fields, package-private implementation, small public API.
- Getters and setters for everything is not encapsulation; behaviour methods are.
- The same principle scales to packages, modules and services (data ownership).