Encapsulation — Explained with Examples
Encapsulation is an object-oriented principle that bundles data and methods together while hiding internal implementation details from outside access.
Encapsulation is one of the four pillars of object-oriented programming (alongside inheritance, polymorphism, and abstraction). It restricts direct access to an object’s internal state and exposes only what is necessary through a controlled interface (getters, setters, methods).
Why Encapsulation Matters
Without encapsulation, any code can modify an object’s internal data — leading to invalid states, tight coupling, and fragile code. Encapsulation protects the integrity of data by enforcing validation and ensuring that internal changes don’t ripple through the codebase.
Real-World Analogy
A vending machine. You interact through the interface (select item, insert coins, retrieve product). You cannot directly access the coin box, the inventory system, or the cooling unit (internal state). The machine’s internals can be redesigned without affecting how you buy a soda. That’s encapsulation.
Example: Encapsulation in Python
# Without encapsulation — anyone can set invalid values
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance # Can be set to -100 directly!
account = BankAccount("Alice", 1000)
account.balance = -500 # No protection — invalid state# With encapsulation — controlled access
class BankAccount:
def __init__(self, owner, initial_balance):
self.owner = owner
self._balance = 0
if initial_balance >= 0:
self._balance = initial_balance
else:
raise ValueError("Initial balance cannot be negative")
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError("Withdrawal must be positive")
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount
@property
def balance(self):
return self._balance # Read-only access, no direct setter
# Usage
account = BankAccount("Alice", 1000)
account.deposit(500)
print(account.balance) # Output: 1500
# account.balance = 0 # AttributeError — encapsulatedRelated Terms
Single Responsibility Principle, Law of Demeter, Separation of Concerns
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro