Tools
Log in
English

Learn to codeJava

Java encapsulation

Based on Java 17List.copyOf · Java 10+

Java encapsulation with a bank account: the bug without it and the private fix.

In one line

Keep an object’s values private and open only a few methods, each with its own checks, as the way to change them.

Why you need it

If any code can change balance, as in the code below, nothing stops the balance from reaching -1700. In a larger program the lines that touch the balance end up in dozens of places, and finding the guilty one takes hours.

Lock balance with private and change it only inside deposit and withdraw, and every check lives in one place. When a rule changes, you edit just those methods.

Everyday picture

Think of a bank counter. Customers never reach into the vault themselves; they ask the teller to deposit or withdraw. Ask for more than you have and the teller says no. The vault is the private field, the counter is the public method.

The bug you get without encapsulation

class Account {    String owner;    int balance;} public class Main {    public static void main(String[] args) {        Account acc = new Account();        acc.owner = "Mina";        acc.balance = 1000;        acc.balance += 500;     // deposit        acc.balance -= 3000;    // withdraw: nobody checks the balance        acc.balance += -200;    // a "deposit" of -200 also goes through        System.out.println(acc.owner + ": " + acc.balance);    }}

When you run it

Mina: -1700

The balance field is open, so nothing checks the balance before a withdrawal. An account that started with 1000 ends at -1700.

The -200 "deposit" also went through. When lines like these are spread across a program, finding the one that broke the balance takes a long time.

Example code

Main.java · 59 lines
import java.util.ArrayList;import java.util.List; class Account {    private final String owner;    private int balance;    private final List<String> history = new ArrayList<>();     Account(String owner, int start) {        if (start < 0) {            throw new IllegalArgumentException("start must be 0 or more");        }        this.owner = owner;        this.balance = start;    }     public void deposit(int amount) {        if (amount <= 0) {            System.out.println("Refused: deposit " + amount);            return;        }        balance += amount;        history.add("+" + amount);    }     public boolean withdraw(int amount) {        if (amount <= 0 || amount > balance) {            System.out.println("Refused: withdraw " + amount);            return false;        }        balance -= amount;        history.add("-" + amount);        return true;    }     public int getBalance() {        return balance;    }     public String getOwner() {        return owner;    }     public List<String> getHistory() {        return List.copyOf(history);    }} public class Main {    public static void main(String[] args) {        Account acc = new Account("Mina", 1000);        acc.deposit(500);        acc.withdraw(3000);        acc.deposit(-200);        acc.withdraw(700);        System.out.println(acc.getOwner() + ": " + acc.getBalance());        System.out.println("History: " + acc.getHistory());    }}

When to use it

  • Fields that must never hold a wrong value (balance, stock, age, password)
  • Changes that must trigger something else (write a history line, send a notice)
  • Lists or arrays you show to the outside. Return a copy or a read-only list.

Adding a getter and setter to every field by habit undoes the hiding. Open only the actions outside code really needs.

List.copyOf exists since Java 10. On older versions, copy with new ArrayList<>(history).

Common mistakes

Adding a setter for everything

With setBalance, hiding the field achieves nothing: anyone can store -999. Replace it with a method that says why the value changes (deposit) and check inside it.

Wrong

class Account {    private int balance;     public int getBalance() {        return balance;    }     public void setBalance(int balance) {        this.balance = balance;    }} public class Main {    public static void main(String[] args) {        Account acc = new Account();        acc.setBalance(-999);        System.out.println(acc.getBalance());    }}

When you run it-999

Fixed

class Account {    private int balance;     public int getBalance() {        return balance;    }     public void deposit(int amount) {        if (amount > 0) {            balance += amount;        }    }} public class Main {    public static void main(String[] args) {        Account acc = new Account();        acc.deposit(-999);        System.out.println(acc.getBalance());    }}

When you run it0

Returning the internal list itself

The field is private, but handing out the list itself lets callers clear() the history. Return a copy.

Wrong

import java.util.ArrayList;import java.util.List; class Account {    private final List<String> history = new ArrayList<>();     void deposit(int amount) {        history.add("+" + amount);    }     List<String> getHistory() {        return history;    }} public class Main {    public static void main(String[] args) {        Account acc = new Account();        acc.deposit(500);        acc.getHistory().clear();        System.out.println(acc.getHistory());    }}

When you run it[]

Fixed

import java.util.ArrayList;import java.util.List; class Account {    private final List<String> history = new ArrayList<>();     void deposit(int amount) {        history.add("+" + amount);    }     List<String> getHistory() {        return new ArrayList<>(history);    }} public class Main {    public static void main(String[] args) {        Account acc = new Account();        acc.deposit(500);        acc.getHistory().clear();        System.out.println(acc.getHistory());    }}

When you run it[+500]

Writing a private field from outside

It does not even compile. That error is encapsulation doing its job. Use the method that was made for it.

Wrong

public class Main {    public static void main(String[] args) {        Account acc = new Account();        acc.balance = 5000;    }}

What javac sayserror: balance has private access in Account

Fixed

public class Main {    public static void main(String[] args) {        Account acc = new Account();        acc.deposit(5000);        System.out.println(acc.getBalance());    }}

When you run it5000

Check yourself

Question 1

An account holds 800. What does the last line show after withdraw(5000)?

public class Main {    public static void main(String[] args) {        Account acc = new Account("Joon", 800);        boolean ok = acc.withdraw(5000);        System.out.println(ok + " " + acc.getBalance());    }}

Show the answer

Answer: 2. false 800 When the amount is more than the balance, it prints a refusal and returns false. The balance does not change.

Question 2

What happens if another class writes acc.balance = 0;?

Show the answer

Answer: 2. It does not compile balance is private, so outside Account you cannot even name it. javac reports "has private access".

Questions people ask

Is encapsulation just writing getters and setters?

Hiding comes first. Make fields private and open only the actions outside code needs. A setter on every field cancels the hiding.

Can a subclass use a private field?

No. Make it protected, or add a method in the parent class, if children need it.

How should I return a list field?

Return a copy with List.copyOf (Java 10+) or new ArrayList<>(list). Handing out the original lets callers add or remove items.