Encapsulation
Overview
Encapsulation is a massive security guard for your data. It means hiding an object's variables from the outside world, and forcing everyone to use specific methods to change those variables.
Imagine a Bank Account. If the `balance` variable is public, a hacker can write `account.balance = 1000000;`. To stop this, we make `balance` private (hidden), and force people to use a `deposit()` method. Inside `deposit()`, we can check if the money is real before updating the balance.
1. Private Variables
The first step of encapsulation is making all the variables in your class `private`. Nobody outside the class can see or touch them.
2. Getters and Setters
To allow safe access, you create `public` methods. A Getter lets the outside world read the data. A Setter lets them change it (but only if they pass your validation rules!).
Syntax
Notice how we prevent negative deposits by controlling access.
public class BankAccount {
// 1. HIDDEN DATA
private double balance = 0;
// 2. GETTER (Read-only access)
public double getBalance() {
return balance;
}
// 3. SETTER (Controlled write access)
public void deposit(double amount) {
if (amount > 0) {
balance += amount; // Safe!
} else {
System.out.println("Nice try, hacker.");
}
}
}Common Pitfalls
- Making variables private, but then writing a Setter that does absolutely no validation. This completely defeats the purpose of encapsulation!
Interview Tips
- Encapsulation is often referred to as 'Data Hiding'. The main goal is to protect the internal state of an object so it never becomes invalid or corrupted.
Real-World Example
Any app that handles users relies on encapsulation. A user's password should never be freely accessible.
public class User {
private String password;
// We only change the password if it's strong enough!
public void setPassword(String newPassword) {
if (newPassword.length() >= 8) {
this.password = newPassword;
}
}
}