Encapsulation
Protecting your data.
Encapsulation
Analogy: security
Encapsulation is like a Vending Machine.
- You cannot reach inside and grab a soda (Private Data).
- You must use the coin slot and buttons (Public Interface).
This protects the machine from being robbed or broken!
Getters and Setters
In code, we use private variables and public methods.
Java Example
Switch language in Navbar
class BankAccount {
private double balance; // Hidden!
public void deposit(double amount) {
if (amount > 0) {
balance += amount; // Safe access
}
}
}
If balance was public, anyone could set it to -1000000! Encapsulation prevents this.
Up Next
Inheritance