🔐 Encapsulation in Java – Explained Simply
Encapsulation is one of the four core Object-Oriented Programming (OOP) principles in Java. It means wrapping data (variables) and code (methods) together as a single unit — and restricting direct access to some of the object’s components.
🧠 Key Idea:
Encapsulation = Data Hiding + Controlled Access
✅ Why Use Encapsulation?
| Benefit | Description |
|---|---|
| 🛡️ Security | Prevent unauthorized access to sensitive data |
| 🧩 Maintainability | Internal code changes won’t affect external code |
| 🎯 Control | Only allow access through specific methods |
| 🔄 Reusability | Code becomes more modular and reusable |
👨💻 How to Achieve Encapsulation in Java
- Declare class variables as
private -
Provide public
getandsetmethods to access and update them
📦 Example: Encapsulation in Action
🔎 Usage:
🚧 Without Encapsulation (Bad Practice):
➡ Anyone can set age = -100, and no one can prevent it!
📌 Summary
| Concept | Description |
|---|---|
| Encapsulation | Binding data and behavior in a single unit |
| Access Modifier | Use private to hide variables |
| Getters/Setters | Use public methods to access/update variables |
| Main Goal | Data protection, abstraction, clean code design |