Encapsulation is the practice of bundling data and the methods that operate on that data inside a class while restricting direct access to the internal state.
Use private fields to prevent direct access from outside the class.
Example 1: Bank Account — Prevent Invalid Balance
Without encapsulation:
class BankAccount {
double balance;
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.balance = 1000;
account.balance = -5000; // ❌ Invalid, but Java allows it
System.out.println(account.balance);
}
}
The problem is that anyone can change the balance to anything.
With encapsulation:
class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(300);
System.out.println(account.getBalance());
}
}
Now the flow becomes:
User
↓
deposit(1000)
↓
Validation
↓
balance
Instead of:
User
↓
balance = anything
This is a very good example because you can explain:
The class decides how its data can be modified.
Suppose marks should always be between 0 and 100.
Without encapsulation:
class Student {
int marks;
}