Encapsulation and Access Modifiers
Site Admin
· 11 Sep 2026
· 11 views
Why Hide Data?
Encapsulation bundles the data of a class with the methods that operate on it, and keeps the data private. Outsiders cannot assign invalid values accidentally because they must go through controlled methods called getters and setters.
Without Encapsulation (the problem)
class BankAccount {
public double balance; // anyone can break the rules
}
BankAccount a = new BankAccount();
a.balance = -500; // negative balance, nothing stops it!With Encapsulation (the fix)
class BankAccount {
private double balance; // hidden from outside
public double getBalance() { return balance; }
public void deposit(double amount) {
if (amount > 0) balance += amount; // rule enforced here
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) balance -= amount;
}
}Now negative deposits are simply ignored, and callers can never put the account into an invalid state directly.
The Access Modifiers
| Modifier | Same class | Same package | Subclass | Anywhere |
|---|---|---|---|---|
| private | Yes | No | No | No |
| (default) | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |
Getters and Setters
class Person {
private int age;
public int getAge() { return age; }
public void setAge(int age) {
if (age >= 0 && age <= 120) {
this.age = age;
}
}
}Key Points
- Encapsulation protects data via private fields and public methods.
- Validation logic lives inside the setter, not scattered in callers.
- Four access levels: private, default (package), protected, public.