Lesson 9 of 23

In progress

Course progress

Java

Encapsulation and getters

Decide what to expose, why a getter is not always safer than a public field, and how to keep invariants without freezing the design.

Encapsulation is often taught as "make fields private and add getters and setters". That is the syntax. The idea is that a class decides what other code may know and change, and that decision is a design choice.

What you will learn

  • Expose behaviour rather than data.
  • Judge when a setter is harmful.
  • Keep a class’s invariants true under every operation.

Private fields, meaningful methods

public class Temperature {
private double celsius;
Temperature(double celsius) {
set(celsius);
}
void set(double celsius) {
if (celsius < -273.15) {
throw new IllegalArgumentException("below absolute zero");
}
this.celsius = celsius;
}
double celsius() {
return celsius;
}
double fahrenheit() {
return celsius * 9 / 5 + 32;
}
}

The field is private, and the only way in is through set, which enforces the physical limit. fahrenheit is behaviour: a caller asks for the value in another unit instead of doing the arithmetic and getting the constant wrong.

Compare with a public field plus a plain setter, which enforces nothing and leaves the conversion to every caller.

Getters are not automatically safe

public class Inventory {
private final java.util.List<String> items = new java.util.ArrayList<>();
java.util.List<String> items() {
return items;   // caller can add and remove
}
}

Returning the list hands over control: a caller can add invalid items, or keep the list and mutate it later. The private keyword bought nothing.

Return an unmodifiable view or a copy:

java.util.List<String> items() {
return java.util.List.copyOf(items);
}

List.copyOf copies and makes the result unmodifiable. Collections.unmodifiableList(items) wraps without copying, so it reflects later changes and is cheaper for a large list that is rarely read. Choose based on whether the caller needs a snapshot.

Setters and invariants

A setter is fine when changing that value is a legitimate operation and the class can keep its rules true. It is harmful when it lets a caller skip a rule.

public class Order {
private String status = "draft";
void pay() {
if (!status.equals("draft")) {
throw new IllegalStateException("cannot pay a " + status + " order");
}
status = "paid";
}
}

There is no setStatus. The only transitions are the ones the domain allows, and each checks the current state. A public setter would let a caller jump from paid to draft and break every report that assumes paid orders stay paid.

When a state machine has more than a few states, model them as an enum and keep the transitions in one method with a switch. The compiler then checks that every state is handled.

Immutability

The strongest form of encapsulation is an object that cannot change:

public record Money(long paise, String currency) {
Money plus(Money other) {
if (!currency.equals(other.currency)) {
throw new IllegalArgumentException("currency mismatch");
}
return new Money(paise + other.paise, currency);
}
}

Immutable objects are safe to share, safe to cache and safe across threads. The cost is allocation on every change, which the JVM handles well for small objects.

Prefer immutability for values: money, dates, ranges, identifiers. Use mutable objects for entities with a lifecycle, where a change is the point.

Package-private as a middle ground

Java has four access levels: private, package-private (no modifier), protected and public. Package-private is underused: it lets a group of related classes collaborate without exposing anything to the rest of the program.

class Parser {          // package-private
Parsed parse(String input) { ... }   // package-private
}

A public facade in the same package calls Parser. Other packages see only the facade, and the internals can change freely.

Encapsulation across layers

The same idea applies at a larger scale. A repository class hides SQL behind methods such as findById, so the service layer does not depend on table names. A controller returns a response object rather than an entity, so a database change does not reshape the API.

The test is dependency: if changing a table requires editing five classes, the boundary leaked.

What not to hide

Encapsulation is not secrecy for its own sake. A class should expose the operations its callers genuinely need, with names that describe the domain. Hiding too much produces a class with thirty narrow methods that force callers to orchestrate internals.

A useful question: what would a caller write if they had the data? If the answer is a calculation the class could do, expose the calculation instead.

Testing encapsulation

Private state is verified through behaviour, which is the point: a test that checks total() after add calls survives a refactor that renames the field.

If a test needs to inspect internals, that is often a signal the class has too many responsibilities, or that a piece of logic should be extracted into something testable on its own.

Generating getters and setters for every field because the IDE offers it. That produces a class with public mutable state behind two layers of syntax, and no invariant is protected.

Write a Playlist class with a private list of track names, an add that rejects duplicates, a remove that returns whether anything was removed, and a tracks() method that returns an unmodifiable snapshot. Explain what a caller can and cannot do.

Show solution
import java.util.ArrayList; import java.util.List; public class Playlist { private final List<String> tracks = new ArrayList<>(); boolean add(String track) { if (track == null || track.isBlank() || tracks.contains(track)) { return false; } tracks.add(track.strip()); return true; } boolean remove(String track) { return tracks.remove(track); } List<String> tracks() { return List.copyOf(tracks); } }

A caller can add unique tracks, remove one, and read a snapshot. They cannot insert a duplicate, add a blank name, or mutate the returned list; an attempt to add to the snapshot throws UnsupportedOperationException. The rules live in one class and hold for every caller.

Recap

  • Private fields plus behaviour protect invariants; private fields plus getters and setters usually do not.
  • Never return a mutable internal collection; copy it or wrap it unmodifiable.
  • Prefer immutable values, and expose domain operations instead of raw state.

Module 4 covers inheritance, polymorphism, interfaces and how to organise classes into packages.

Is a getter always better than a public field?
Only if it can change without breaking callers, or if it hides a computation. A trivial getter over a mutable field adds syntax, not safety.
What does protected allow?
Access from subclasses and from the same package. It is the loosest sensible level for an extension point.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.