Module 5 · Classes and Objects — topic 4 of 4
Encapsulation and Access Modifiers
Hiding fields with private, exposing behaviour through methods, getters and setters done well, the four access levels, packages and immutable classes.
Learning objectives
- Use private fields with public methods to protect an object's state
- Explain public, protected, package-private and private
- Design an immutable class
Definition
Encapsulation is the principle of keeping an object's data private and allowing access only through a controlled public interface of methods, so that the object can enforce its own rules (invariants).
Introduction
If any code can write account.balance = -1_000_000;, no amount of careful withdrawal logic will keep the balance valid. Encapsulation fixes this: the field is private, and the only way to change the balance is through methods like deposit and withdraw that check the rules.
Why it matters
Encapsulation is the first pillar of object-oriented design and the basis of maintainable code: you can change how a class stores its data without breaking code that uses it.
Interviewers routinely ask about access modifiers and immutability.
Detailed explanation
Access levels, from most to least open: public (everywhere), protected (same package and subclasses), *package-private* (no keyword: same package only) and private (same class only).
The usual pattern. Fields are private; behaviour is public. Methods validate their inputs and keep the object's invariants — rules that are always true, such as 'balance is never negative'.
Getters and setters. A getter (getBalance()) exposes a value read-only; a setter (setEmail(...)) allows controlled change. Don't add setters automatically: many fields should only change through meaningful operations (deposit), or never.
Defensive copies. If a getter returns a mutable internal object, such as a list, callers can change your private data through it. Return an unmodifiable view (List.copyOf(list) or Collections.unmodifiableList) instead.
Immutable classes never change after construction: make the class final, all fields private final, provide no setters, and copy mutable inputs and outputs. String, Integer and LocalDate are immutable, which makes them safe to share between objects and threads.
Packages group related classes (com.kenholt.bank) and form the boundary for package-private access. A package statement at the top of a file names its package; import brings classes from other packages into scope.
Syntax
- Most fields should be private.
- Expose operations (deposit) rather than raw setters (setBalance).
- Return copies or unmodifiable views of internal collections.
Code examples
Protecting a balance
true -> 3000 false -> 3000 Error: deposit must be positive
A validating setter
true asha@example.com false asha@example.com
More examples
Defensive copies and an immutable class
Asha [Java, SQL] skills() is read-only Asha [Java, SQL] Asha [Java, SQL, Spring]
Step-by-step explanation
List.copyOf(skills)copies the caller's list into a new unmodifiable list, so later changes toinputcan't reach inside the resume.skills()can safely return the internal list because it is unmodifiable;addon it throws UnsupportedOperationException.- The class is
finaland its fields areprivate final, so neither subclasses nor methods can change a Resume after construction. withSkillfollows the immutable style: instead of changing the object it returns a new one with the extra skill.- Printing
ragain shows it is unchanged, whiler2has three skills.
Expected output
Running “Defensive copies and an immutable class” prints exactly:
Practical applications
- Bank, inventory and booking systems that must keep invariants
- Immutable value objects (Money, LocalDate) shared freely across code and threads
- Library APIs that hide implementation details so they can change internally
Best practices
- Start with everything private and open up only what is needed.
- Prefer meaningful operations to generic setters.
- Make value classes immutable whenever possible.
Common mistakes
Public mutable fields
Avoid
Prefer
Anyone can set total to any value; private fields let the class control and validate changes.
Leaking an internal list
Avoid
Prefer
Returning the internal list lets callers add or remove items without going through your validation.
Important notes
- Records (module 7) are a concise way to write immutable data classes.
- Encapsulation is enforced by the compiler; reflection can bypass it, but that is a deliberate, special-purpose tool.
Key takeaways
- Keep fields private and expose behaviour through methods that enforce invariants.
- Access levels: public > protected > package-private > private.
- Immutable classes are final with private final fields and defensive copies.
Try it yourself
- 1Write a
Thermostatclass whose target temperature can only be set between 16 and 30. - 2Make a
Matrix2x2class immutable, with amultiplymethod that returns a new matrix.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
5 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhich access modifier restricts a field to its own class?
- BeginnerWhy make a balance field private and provide deposit/withdraw methods?
- ModerateWhat is printed?