Lesson 3 of 12 · 9 min · Object-oriented Java
Encapsulation, access modifiers and immutability
What you will learn
- What encapsulation is and why it protects your code
- The four access levels:
private, package-private,protected,public - Getters, setters and validation
- Build immutable classes and avoid leaking mutable internals
- Why
Stringis immutable and what it means for you
In simple words
Think of a bank locker. You cannot reach into the vault and rearrange the money. You ask the clerk to deposit or withdraw, and the clerk checks the rules. Encapsulation means a class keeps its data private and only lets others change it through methods that enforce the rules. If anyone could set the balance to minus a million directly, bugs would be impossible to track down.
Words to know
- Encapsulation: bundling data with the methods that use it, and hiding the data.
- Access modifier: a keyword that controls who can see a member.
- Immutable: an object that cannot change after it is created.
- Defensive copy: copying a mutable object so outside code cannot change your internals.
The problem without encapsulation
public class Account {
public double balance; // anyone can do account.balance = -1_000_000
}
Every piece of code that touches balance must remember the rules (never negative, record every change), and one mistake corrupts the data. Encapsulation puts the rules in one place:
public class Account {
private double balance; // hidden
public double balance() { return balance; } // read access
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
balance += amount;
}
public void withdraw(double amount) {
if (amount <= 0 || amount > balance) throw new IllegalArgumentException("invalid amount");
balance -= amount;
}
}
The only way to change the balance is through methods that validate. Later you can change how balance is stored (paise as a long, a ledger of transactions) without touching callers: the public surface stays the same. That is the main benefit: freedom to change the inside.
Access modifiers
| Modifier | Visible to |
|---|---|
private |
the same class only |
| (none): package-private | classes in the same package |
protected |
the same package, and subclasses anywhere |
public |
everyone |
Guidelines: make fields private; make methods only as visible as they need to be; expose a small public API. Java 9 modules (module-info.java) can hide whole packages from other modules. Keep your public API small, because everything public is a promise you must keep.
Getters and setters
JavaBeans-style code often has getName() and setName(...). Frameworks such as Spring, JPA and Jackson rely on these conventions or on fields. A few rules:
- Provide a getter where outsiders need to read; provide a setter only where outsiders really should be allowed to change the value, and validate inside it.
- Do not generate setters for every field automatically: that destroys encapsulation, because it again lets anyone set anything.
- Prefer meaningful methods over setters:
account.deposit(100),order.markPaid()rather thansetStatus("PAID"). - For read-only data, records give you accessors and no setters.
Validate in the constructor
An object should never exist in an invalid state:
public class Customer {
private final String email;
public Customer(String email) {
if (email == null || !email.contains("@")) {
throw new IllegalArgumentException("invalid email: " + email);
}
this.email = email.trim().toLowerCase();
}
public String email() { return email; }
}
Objects.requireNonNull(value, "message") is the standard null check.
Immutable classes
An immutable object never changes after construction. String, Integer, LocalDate and records are immutable. Benefits: safe to share between threads without locks, safe as map keys and set members, simple to reason about, and cache-friendly.
To write an immutable class:
- Make the class
final(or all constructors private) so subclasses cannot add mutability. - Make all fields
private final. - Provide no setters.
- Copy any mutable object passed in or returned (defensive copies).
public final class Order {
private final int id;
private final List<String> items;
public Order(int id, List<String> items) {
this.id = id;
this.items = List.copyOf(items); // defensive copy, and unmodifiable
}
public int id() { return id; }
public List<String> items() { return items; } // safe: List.copyOf is unmodifiable
}
Without the copy, the caller could keep a reference to the original list and change it after construction, silently changing your "immutable" order:
var list = new ArrayList<>(List.of("pen"));
var order = new Order(1, list); // if we stored list directly...
list.add("laptop"); // ...the order would now contain a laptop
Likewise, never return an internal mutable collection or a Date; return an unmodifiable view or a copy (List.copyOf, Collections.unmodifiableList) or use immutable types such as java.time.LocalDate. Note that final on a field only stops reassignment of the reference; it does not make the object it points to immutable.
A record gives you most of this, but a record that holds a mutable list still shares it; copy in a compact constructor: public Order { items = List.copyOf(items); }.
"Changing" an immutable object
You create a new one. Immutable classes often have "wither" methods:
public Order withId(int newId) { return new Order(newId, items); }
String works this way: s.toUpperCase() returns a new string and leaves s unchanged. Building a long string with + in a loop creates many temporary strings; use StringBuilder in loops:
var sb = new StringBuilder();
for (String part : parts) sb.append(part).append(',');
String joined = sb.toString();
Why String is immutable
- Security: strings hold file paths, URLs and usernames; if they could change after validation, checks could be bypassed.
- Thread safety: shared without synchronisation.
- Caching and the string pool: identical literals share one object (
"abc" == "abc"is usually true for literals, but always compare strings withequals, never==). - Hash caching: the
hashCodeis computed once and reused, which makes strings fast map keys.
Encapsulation beyond classes
- Keep packages cohesive; use package-private classes for internal helpers.
- Use interfaces to hide implementation: callers depend on
PaymentMethod, notUpiPayment. - Law of Demeter: talk to your direct collaborators, not to a chain of their internals (
order.customer().address().city()leaks structure). - Tell, don't ask: instead of reading state and deciding outside (
if (account.balance() >= x) account.setBalance(...)), tell the object what to do (account.withdraw(x)).
Common mistakes
- Public fields.
- Auto-generated setters for everything.
- Returning internal mutable lists (
return items;). - Storing a caller's mutable object without a copy.
- Believing
finalmakes an object immutable. - Comparing strings with
==.
Try it yourself
- Write an
Accountwith private balance,depositandwithdrawrules, and test the invalid cases. - Turn a class with setters into an immutable one with a constructor that validates.
- Show the bug when you store the caller's list directly, then fix it with
List.copyOf. - Write a loop that builds a string with
+, then withStringBuilder, and explain the difference.
Check yourself
What is encapsulation and why is it useful?
Hiding a class's data behind methods that enforce the rules. It keeps objects valid and lets you change the internals without breaking callers.
What does final on a field mean for a List field?
The reference cannot be reassigned, but the list's contents can still change unless the list itself is immutable.
What are the steps to make a class immutable?
Make it final, make fields private final, provide no setters, and make defensive copies of mutable inputs and outputs.
Why is String immutable?
For security, thread safety, string pooling and cached hash codes, which make it safe and fast to share and use as a key.
Interview questions
How do you create an immutable class in Java?
Declare it final, keep all fields private and final, do not provide mutators, initialise everything in the constructor, and defensively copy any mutable object that comes in or goes out. Records and List.copyOf help.
What is the difference between private, protected and package-private?
private is visible only inside the class; package-private (no modifier) inside the package; protected inside the package and in subclasses; public everywhere.
What is a defensive copy and when is it needed?
A copy of a mutable argument or field made so that outside code cannot modify the object's internal state after the fact; needed in constructors, setters and getters that handle mutable types such as collections and arrays.
Summary
- Make fields private and expose behaviour through small, validating methods.
- Keep the public API small; use the right access modifier.
- Immutable objects (final class, final fields, no setters, defensive copies) are safe and simple;
finalalone does not make contents immutable. - Strings are immutable; compare with
equalsand useStringBuilderin loops.
Going deeper
- dev.java: Access control: the access modifiers in the official guide.
- The Java Tutorials: Controlling access to members of a class: the access table.
- A strategy for defining immutable objects: the Oracle tutorial's checklist.
- Immutable collection factory methods:
List.of,Set.of,Map.ofandcopyOf.
See how much of this you can explain
A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.