🔹 Encapsulation
**Encapsulation** is one of the fundamental principles of **Object-Oriented Programming (OOP)**. It is the concept of **hiding the internal details** of an object and only exposing the necessary parts through a controlled interface.
📌 Why Use Encapsulation?
Encapsulation helps in **data protection, modularity, and maintainability**.
- ✅ **Data Hiding** – Prevents direct modification of internal data.
- ✅ **Improves Security** – Restricts access to sensitive information.
- ✅ **Enhances Maintainability** – Changes can be made internally without affecting external code.
💡 Real-Life Example
Consider a **Bank Account** where the balance should not be directly accessible. Instead, we provide **getter and setter methods** to control access.
🖥️ Encapsulation in Java
In Java, we achieve encapsulation by using **private variables** and **public methods**.
class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
account.deposit(500);
System.out.println("Balance: " + account.getBalance());
}
}
🖥️ Encapsulation in Python
In Python, encapsulation is implemented using **private attributes** (prefixing with **_ or __**).
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
account = BankAccount(1000)
account.deposit(500)
print("Balance:", account.get_balance())
🎯 Summary
**Encapsulation** is a crucial OOP concept that helps in **data security, modular programming, and ease of maintenance** by **restricting direct access** to object properties.