Thuta Learning
Java
AdvancedProgrammingBeginner

Encapsulation

JavaLesson 2230 min

What you'll walk away with

  • Keep fields private and expose them through getters and methods that validate
  • Enforce one invariant in both the constructor and the setter
  • Explain why not every field needs a setter and what final fields buy you
  • Guard mutable lists with defensive copies and use a record for simple immutable data

Explain it simply

Encapsulation in plain language

Encapsulation means locking an object's data away from direct outside access and letting people read or change it only through public methods. If anyone can edit the data freely, impossible values such as an age of -5 or a negative bank balance can sneak in. When every change goes through a method, the class can check it at the door.

Think of an ATM. The cash sits in a locked safe, and you withdraw it only through the screen and buttons. The machine checks your PIN and never lets you take more than your balance. Leave the safe open and none of those rules mean anything.

Problem → Why → Solution

The problem: a public field stops nobody

In a gym membership app, the Member class has public age and credits fields. A form writes member.age = -5 without checking the input, and a refund feature runs member.credits -= 100 without looking at the balance. When the bug report arrives, there are a hundred places that touch these fields, and no easy way to tell which one broke the data.

Member.java
class Member {
  public int age;
  public int credits;
}

member.age = -5;          // nothing stops this
member.credits -= 100;    // credits can go below zero

Keep the rule in one place

Rules such as "age is never negative" and "credits never drop below zero" are called invariants. With public fields, every place that edits them must remember the rules on its own. Make the fields private and force every change through a method, and the rule lives in one place inside the class, where bad values are refused at the entrance.

Core concept: private data, guarded entrances

Encapsulation has two parts. The first is bundling data with the methods that work on it inside one class; the second is hiding the class's internal representation. The private modifier from lesson 18 is the tool for the second part: only the class's own code can touch a private field, and writing person.age = -5 from outside is a compile error, "age has private access in Person".

Generating a getter and setter for every private field is not encapsulation by itself: a setAge(int) that checks nothing is a public field with extra steps. The real job is protecting invariants, rules that hold from the moment an object is built and at every moment afterwards. So the check belongs in the setter and in the constructor, because the constructor is another way in. Instead of silently ignoring a bad value, throw IllegalArgumentException so the caller learns about the mistake immediately.

Not every field needs a setter. Fields that should never change after construction, such as a name or an ID, can be private final and set once in the constructor; after that nobody can change them. When a value does change, meaningful methods such as deposit(amount) and withdraw(amount) express the change better than a bare setBalance(x), and they make the rule easy to check.

private protects the reference, not the object it points to. If a getter returns a private List field directly, the caller can call list.add(...) and change your object's insides. So copy mutable collections on the way in and on the way out (defensive copies); List.copyOf() returns an unmodifiable copy, which makes it a good fit for the job.

An object is a guarded room
  1. Fields stay inside the room (private)
  2. Methods are the only doors
  3. Every door checks the rules
  4. Bad values are refused with an exception

The constructor is a door too, and a getter that returns a mutable object is a hole in the wall.

General pattern

java
class Thing {
  private final Type fixedField;     // set once, never changes
  private Type changingField;

  Thing(Type fixed, Type changing) { ...validate, then assign... }
  Type getChangingField() { return changingField; }

  void changeSafely(Type newValue) {
    if (!isValid(newValue)) throw new IllegalArgumentException("...");
    changingField = newValue;
  }
}

Every field is private, the ones that should not change are final, and every change passes through a method that validates and throws when the value is wrong.

Worked example: a Person that protects its age

Person's name is final, so it has no setter; age can change but must stay between 0 and 150. The check lives in one private helper method, used by both the constructor and setAge(). When main tries -5, it gets an exception, and the last line proves the age did not change.

About try/catch

This example catches the thrown exception with try/catch. The Exceptions lesson covers the details; here it only shows that setAge(-5) is refused.

Main.java
public class Main {
  public static void main(String[] args) {
    Person person = new Person("Aung", 25);
    System.out.println(person.getName());
    System.out.println(person.getAge());

    person.setAge(26);
    System.out.println(person.getAge());

    try {
      person.setAge(-5);
    } catch (IllegalArgumentException e) {
      System.out.println("Rejected: " + e.getMessage());
    }
    System.out.println(person.getAge());
    // person.age = -5;   // compile error: age has private access in Person
  }
}

class Person {
  private final String name;
  private int age;

  Person(String name, int age) {
    this.name = name;
    this.age = checkAge(age);
  }

  public String getName() {
    return name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int newAge) {
    age = checkAge(newAge);
  }

  private static int checkAge(int age) {
    if (age < 0 || age > 150) {
      throw new IllegalArgumentException("age must be between 0 and 150, got " + age);
    }
    return age;
  }
}

Code breakdown

  1. Private fieldsprivate int age;

    Only Person's own code can touch age. Uncomment person.age = -5 in main and the program stops compiling.

  2. Never changesprivate final String name;

    Being final, it is assigned once in the constructor and there is no setName(). When a value should never change, leaving out the setter is the strongest protection.

  3. One rule, used twicethis.age = checkAge(age);

    The constructor also goes through checkAge(), so new Person("X", -5) is refused as well. The rule is written once, so changing it means editing one place.

  4. Loud rejectionthrow new IllegalArgumentException("age must be between 0 and 150, got " + age);

    Instead of quietly skipping the bad value, it throws an exception whose message says why. The object stays in its previous valid state.

You should see
Aung
25
26
Rejected: age must be between 0 and 150, got -5
26

Defensive copies: when a private list only looks safe

LeakyTeam and SafeTeam both have a private final List field. The difference is that LeakyTeam stores the caller's list as it is, while SafeTeam copies it with List.copyOf(). When the caller edits its original list, LeakyTeam changes too.

Teams.java
import java.util.ArrayList;
import java.util.List;

public class Teams {
  public static void main(String[] args) {
    List<String> names = new ArrayList<>(List.of("Aye", "Bo"));
    LeakyTeam leaky = new LeakyTeam(names);
    SafeTeam safe = new SafeTeam(names);

    names.add("Intruder");                  // the caller edits its own list
    System.out.println(leaky.members());    // [Aye, Bo, Intruder]
    System.out.println(safe.members());     // [Aye, Bo]

    try {
      safe.members().add("Hacker");
    } catch (UnsupportedOperationException e) {
      System.out.println("SafeTeam cannot be changed from outside");
    }
  }
}

class LeakyTeam {
  private final List<String> members;
  LeakyTeam(List<String> members) { this.members = members; }   // shares the list
  List<String> members() { return members; }                    // hands it out
}

class SafeTeam {
  private final List<String> members;
  SafeTeam(List<String> members) { this.members = List.copyOf(members); }
  List<String> members() { return members; }   // already unmodifiable
}

final does not make the list immutable

private final List<String> members only means the members variable cannot be pointed at a different list. final does not stop anyone adding or removing elements; List.copyOf() is what makes the list unmodifiable.

Records: a shortcut for immutable data

A record, available since Java 16, generates private final fields, a constructor, accessor methods, equals(), hashCode() and toString() from a single line. It has no setters, so it cannot change after it is built. You can put validation in a compact constructor (one written without a parameter list), so an invalid record can never be created.

Records.java
public class Records {
  public static void main(String[] args) {
    Temperature today = new Temperature(21.5);
    System.out.println(today);             // Temperature[celsius=21.5]
    System.out.println(today.celsius());   // accessor, not getCelsius()

    try {
      new Temperature(-300);
    } catch (IllegalArgumentException e) {
      System.out.println(e.getMessage());
    }
  }
}

record Temperature(double celsius) {
  Temperature {                            // compact constructor
    if (celsius < -273.15) {
      throw new IllegalArgumentException("below absolute zero: " + celsius);
    }
  }
}

This program prints three lines: Temperature[celsius=21.5], 21.5 and below absolute zero: -300.0. Records suit values that carry data; for objects whose state changes, like an account with deposit and withdraw, keep using a normal class.

In real projects

Encapsulation in real projects

In classes that hold money, permissions or subscription status, encapsulation is a security requirement. A Wallet class that offers no setBalance(), only credit() and debit(), makes a negative balance or an unrecorded transfer impossible. Want to add logging? Every change already passes through those methods, so it goes in one place.

  • The JDK's String is immutable and never hands out its internal character array, which is why strings can be shared safely between threads and used as HashMap keys.
  • java.time classes such as LocalDate are immutable, and plusDays() returns a new object, so a getter can return a LocalDate directly. The old java.util.Date is mutable and needs copying.
  • In an API layer, accepting request data as a record (for example CreateUserRequest) that validates in its compact constructor means an invalid request never reaches the service layer.

Common mistakes

Common mistakes with encapsulation

Generating unchecked setters for everything

An IDE can generate a getter and setter for every field in one click. But setCredits(int c) { credits = c; } is a public field in disguise and happily accepts -100. Before adding a setter, ask whether outside code really needs to change this field and, if so, what rule applies.

Validating in the setter but not the constructor

If setAge() rejects negatives but Person(String name, int age) { this.age = age; } does not, new Person("Aung", -5) creates an invalid object at birth. Put the validation in one helper method and call it from both entrances.

Returning a mutable collection directly

If getOrders() returns the private List itself, a caller can wipe every order with getOrders().clear() without any of the class's checks running. Return List.copyOf() or Collections.unmodifiableList() and allow changes only through methods such as addOrder().

Silently ignoring bad values

A setter like if (newAge >= 0) age = newAge; rejects -5 but tells the caller nothing, so the program carries on believing the age changed. Bugs like that are very hard to trace. Throwing an exception makes the problem visible at the exact spot where it happened.

Mini challenge

Mini challenge: a bank account

Write a BankAccount class whose balance can never go negative. Only deposit() and withdraw() may change it, and every operation is recorded in a history. The history must be read-only for outside code.

  • Keep balance and history private, with no setBalance()
  • deposit() rejects zero or negative amounts with IllegalArgumentException
  • withdraw() rejects amounts above the balance with an exception that has a message
  • history() returns an unmodifiable list, and main's attempt to add() to it fails
Bank.java
import java.util.ArrayList;
import java.util.List;

public class Bank {
  public static void main(String[] args) {
    BankAccount account = new BankAccount();
    // TODO: deposit 100, withdraw 30
    // TODO: try to withdraw 500 and print "Rejected: <message>"
    // TODO: try to add a fake entry to history() and print "History is read-only"
    // TODO: print the balance and the history
  }
}

class BankAccount {
  // TODO: private long balance and a private List<String> history

  void deposit(long amount) {
    // TODO: validate, update balance, record "deposit <amount>"
  }

  void withdraw(long amount) {
    // TODO: validate against the balance, update, record "withdraw <amount>"
  }

  // TODO: getBalance() and a read-only history()
}

Expected: Four lines: Rejected: insufficient funds: balance 70, requested 500, then History is read-only, then Balance: 70, then History: [deposit 100, withdraw 30].

Show hint

Validate before changing the balance, so the object is untouched when an exception is thrown. Returning List.copyOf(history) from history() makes a caller's add() throw UnsupportedOperationException. Storing money as a long rather than a double avoids rounding errors.

Show solution
Bank.java
import java.util.ArrayList;
import java.util.List;

public class Bank {
  public static void main(String[] args) {
    BankAccount account = new BankAccount();
    account.deposit(100);
    account.withdraw(30);

    try {
      account.withdraw(500);
    } catch (IllegalArgumentException e) {
      System.out.println("Rejected: " + e.getMessage());
    }

    try {
      account.history().add("deposit 1000000");
    } catch (UnsupportedOperationException e) {
      System.out.println("History is read-only");
    }

    System.out.println("Balance: " + account.getBalance());
    System.out.println("History: " + account.history());
  }
}

class BankAccount {
  private long balance;
  private final List<String> history = new ArrayList<>();

  void deposit(long amount) {
    if (amount <= 0) {
      throw new IllegalArgumentException("deposit must be positive, got " + amount);
    }
    balance += amount;
    history.add("deposit " + amount);
  }

  void withdraw(long amount) {
    if (amount <= 0) {
      throw new IllegalArgumentException("withdrawal must be positive, got " + amount);
    }
    if (amount > balance) {
      throw new IllegalArgumentException(
          "insufficient funds: balance " + balance + ", requested " + amount);
    }
    balance -= amount;
    history.add("withdraw " + amount);
  }

  long getBalance() {
    return balance;
  }

  List<String> history() {
    return List.copyOf(history);
  }
}

Quick quiz 1 / 3

Using a setter like void setAge(int a) { if (a >= 0) age = a; }, what does p.setAge(30); p.setAge(-5); System.out.println(p.getAge()); print?

Quick quiz 2 / 3

What is wrong with class Course { private final List<String> students; Course(List<String> s) { students = s; } List<String> getStudents() { return students; } }?

Quick quiz 3 / 3

Which design best guarantees that an Account's balance never goes negative?

What to remember

  • Encapsulation is not just private fields; it is protecting the object's invariants.
  • Run the same check in the constructor and in every method that changes state, and throw when it fails.
  • Make fields that should not change final with no setter, and express changes through meaningful methods like deposit().
  • Copy mutable collections on the way in and out, and use a record for simple immutable data.

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Encapsulation | Thuta Learning