Skip to content

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.

Beginner 15 min read·Lesson 19 of 39 in Java Programming

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

Java
public class BankAccount {
private long balance; // hidden state
public long getBalance() { return balance; } // read-only access
public void deposit(long amount) { // controlled change
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
balance += amount;
}
}
  • 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

Java
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount("Asha");
acc.deposit(5_000);
System.out.println(acc.withdraw(2_000) + " -> " + acc.getBalance());
System.out.println(acc.withdraw(10_000) + " -> " + acc.getBalance());
try {
acc.deposit(-50);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
// acc.balance = 1_000_000; // does not compile: balance is private
}
}
class BankAccount {
private final String owner;
private long balance;
BankAccount(String owner) { this.owner = owner; }
public long getBalance() { return balance; }
public String getOwner() { return owner; }
public void deposit(long amount) {
if (amount <= 0) throw new IllegalArgumentException("deposit must be positive");
balance += amount;
}
public boolean withdraw(long amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
}
Output
true -> 3000
false -> 3000
Error: deposit must be positive

A validating setter

Java
public class Main {
public static void main(String[] args) {
User u = new User("asha");
System.out.println(u.setEmail("asha@example.com") + " " + u.getEmail());
System.out.println(u.setEmail("not-an-email") + " " + u.getEmail());
}
}
class User {
private final String username;
private String email = "";
User(String username) { this.username = username; }
public String getEmail() { return email; }
public boolean setEmail(String email) {
if (email == null || !email.matches("[^@\\s]+@[^@\\s]+\\.[a-z]{2,}")) return false;
this.email = email;
return true;
}
}
Output
true asha@example.com
false asha@example.com

More examples

Defensive copies and an immutable class

Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> input = new ArrayList<>(List.of("Java", "SQL"));
Resume r = new Resume("Asha", input);
input.add("Hacking"); // caller changes its own list
System.out.println(r); // resume is unaffected
try {
r.skills().add("Cheating");
} catch (UnsupportedOperationException e) {
System.out.println("skills() is read-only");
}
Resume r2 = r.withSkill("Spring"); // 'modifying' returns a new object
System.out.println(r);
System.out.println(r2);
}
}
final class Resume {
private final String name;
private final List<String> skills;
Resume(String name, List<String> skills) {
this.name = name;
this.skills = List.copyOf(skills); // defensive, unmodifiable copy
}
public String name() { return name; }
public List<String> skills() { return skills; }
public Resume withSkill(String skill) {
List<String> more = new ArrayList<>(skills);
more.add(skill);
return new Resume(name, more);
}
@Override public String toString() { return name + " " + skills; }
}
Output
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 to input can't reach inside the resume.
  • skills() can safely return the internal list because it is unmodifiable; add on it throws UnsupportedOperationException.
  • The class is final and its fields are private final, so neither subclasses nor methods can change a Resume after construction.
  • withSkill follows the immutable style: instead of changing the object it returns a new one with the extra skill.
  • Printing r again shows it is unchanged, while r2 has three skills.

Expected output

Running “Defensive copies and an immutable class” prints exactly:

TextOutput
Asha [Java, SQL]
skills() is read-only
Asha [Java, SQL]
Asha [Java, SQL, Spring]

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

public class Order { public double total; }

Prefer

public class Order {
private double total;
public double getTotal() { return total; }
}

Anyone can set total to any value; private fields let the class control and validate changes.

Leaking an internal list

Avoid

public List<Item> getItems() { return items; }

Prefer

public List<Item> getItems() { return List.copyOf(items); }

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

  1. 1
    Write a Thermostat class whose target temperature can only be set between 16 and 30.
  2. 2
    Make a Matrix2x2 class immutable, with a multiply method 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?
Practise this topic