JOOPs Through Java
All lessons

Unit 3 · Classes and Objects · 9 min

Encapsulation

Encapsulation means keeping data private inside a class and giving controlled access through public getter and setter methods.

Why this matters

It protects your object from invalid data and lets you change the inside of a class later without breaking other code.

Real-life analogy

An ATM encapsulates the cash. You cannot reach inside the machine; you request money through buttons, and the machine checks your balance first.

Example

Java
class BankAccount {
    private String holder;
    private double balance;

    public BankAccount(String holder, double balance) {
        this.holder = holder;
        this.balance = balance;
    }

    public String getHolder() {
        return holder;
    }

    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            System.out.println("Invalid deposit amount");
            return;
        }
        balance += amount;
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            System.out.println("Insufficient balance");
            return;
        }
        balance -= amount;
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount("Ananya Rao", 5000);
        acc.deposit(1500);
        acc.withdraw(10000);
        System.out.println(acc.getHolder() + " balance: " + acc.getBalance());
    }
}

Output

Insufficient balance
Ananya Rao balance: 6500.0

Step by step

  1. 1Both fields are private, so `acc.balance = -999;` is impossible from outside.
  2. 2getHolder() and getBalance() are getters: read-only access.
  3. 3deposit() and withdraw() are the only ways to change balance, and each validates first.
  4. 4withdraw(10000) is rejected because the balance is only 6500.

Key points

  • private fields + public methods = encapsulation
  • Getters read, setters write, and setters can validate
  • Also called data hiding
  • Makes future changes safe

Common mistakes

  • Writing getters and setters for everything without any validation
  • Leaving one field public and breaking the whole protection

Try it yourself

  • Encapsulate a Student class so marks can never be set below 0 or above 100.
  • Add a toString()-style display method that shows account details safely.
Open the practice notebook