Β
π Encapsulation in Java β Data Security Made Simple
When we talk about OOP in Java, one of the most powerful principles is Encapsulation. Think of it as putting sensitive data inside a box and only opening it with a proper key (methods).
π What is Encapsulation?
π Encapsulation is the process of hiding data (variables) inside a class and providing controlled access using methods (getters & setters).
It prevents direct access to data and protects it from unwanted modification.
π¦ Real-World Analogy
-
Imagine your ATM card & PIN.
-
Your bank balance (data) is hidden.
-
You canβt directly take money out from the vault.
-
You use an ATM machine (methods) to access your balance safely.
-
Thatβs Encapsulation in action!
β‘ Key Points of Encapsulation
-
β Class variables are kept private.
-
β Public methods (getters & setters) are used to access or modify data.
-
β Provides data security.
-
β Increases code maintainability & flexibility.
π₯οΈ Java Example: Encapsulation in Action
class BankAccount {
// Private data
private String accountHolder;
private double balance;
// Getter method
public String getAccountHolder() {
return accountHolder;
}
// Setter method
public void setAccountHolder(String name) {
this.accountHolder = name;
}
// Getter method
public double getBalance() {
return balance;
}
// Setter method
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.setAccountHolder("Ravi");
acc.deposit(5000);
System.out.println("Account Holder: " + acc.getAccountHolder());
System.out.println("Balance: " + acc.getBalance());
}
}
β Output:
Account Holder: Ravi
Balance: 5000.0
π― Benefits of Encapsulation
-
π Security β Data is safe from unauthorized access.
-
π Flexibility β Easy to change the code later without breaking other parts.
-
π¦ Reusability β Encapsulated classes can be reused across projects.
-
π Maintainability β Changes in one part donβt affect the whole program.
β¨ Quick Summary
π Encapsulation = Data + Methods bundled together in a class with restricted access.
It ensures security, control, and clean code architecture.
π‘ Pro Tip: Always make your variables private and provide public getter/setter methods when needed.
Β