What is Encapsulation?

Bundling data and methods together while controlling access to that data.

Introduction

Encapsulation is one of the four pillars of OOP. It means bundling data and the methods that operate on that data together inside a class, and controlling who can access or modify that data. It is about protection and organization.

The Concept

Think of a capsule or pill -- it wraps medicine inside a protective shell. You take the pill (interact with it), but you never directly touch the medicine inside. Encapsulation does the same with data: it wraps it inside a class and controls how the outside world interacts with it.

Two Parts of Encapsulation

1. Bundling

Data (attributes) and methods (functions) live together inside a class. A BankAccount class keeps the balance and the deposit method in the same place.

2. Access Control

Restricting direct access to some of the data. Instead of letting anyone change the balance directly, you force them to use a method like deposit().

Why Encapsulation Matters

  • Prevents accidental modification: No one can set a balance to a negative number by mistake.
  • Makes code safer and more predictable: Data changes only through controlled methods.
  • Hides internal complexity: Users of your class do not need to know how things work inside.

Without Encapsulation (The Problem)

class BankAccount:
    def __init__(self, balance):
        self.balance = balance

acc = BankAccount(1000)
acc.balance = -500  # ANYONE can set invalid values!
print(acc.balance)  # -500 — this should not be allowed

There is nothing stopping someone from directly setting the balance to a negative number. The class has no protection over its own data.

With Encapsulation (The Fix)

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # private attribute

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def get_balance(self):
        return self.__balance

acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance())  # 1500
# acc.__balance = -500    # This won't work as expected!

What changed: The balance is now private (__balance). The only way to add money is through deposit(), which validates the amount. The only way to read it is through get_balance().

Real-World Analogy

A car's engine is encapsulated. You interact with the car through a public interface -- the steering wheel, pedals, and gear shift. You do not directly manipulate the engine's internal wiring, fuel injectors, or pistons. The complexity is hidden; only safe, controlled actions are exposed.

Banking

You cannot directly change your account balance. You must go through deposit and withdrawal transactions.

Medical Records

Patient data is not publicly accessible. Only authorized personnel can view or update records through controlled systems.

Passwords

A login system never lets you read the stored password directly. You can only verify it through a controlled check.

OOP Terms

  • Encapsulation: Bundling data and methods together inside a class, and restricting direct access to the internal data.
  • Public Interface: The methods and attributes that are accessible from outside the class -- the "controls" you expose.
  • Data Hiding: The practice of making internal data private so it cannot be accessed or modified directly.

Best Practices

  • Make attributes private by default, and provide methods to access or modify them with validation.
  • Keep your public interface simple -- only expose what users of the class actually need.
  • Think about what could go wrong if someone directly modified an attribute, then protect against it.

Common Mistakes

  • Making everything public -- this defeats the purpose of encapsulation.
  • Thinking encapsulation is only about hiding data -- it is also about bundling related data and behavior together.
  • Over-encapsulating simple classes that do not need protection (e.g., a simple Point with x, y coordinates).

Practice Exercises

  1. Create a Password class that stores a private password. Add a check_password(guess) method that returns True or False, but never reveals the actual password.
  2. Create a Temperature class with a private __celsius attribute. Add a set_temperature() method that only accepts values between -273.15 and 1000.
  3. Take the unprotected BankAccount example and add a withdraw() method that prevents the balance from going negative.

Summary

  • Encapsulation bundles data and methods together and controls access to internal data.
  • It has two parts: bundling (data + methods in a class) and access control (restricting direct access).
  • Without encapsulation, anyone can set invalid values on your objects.
  • With encapsulation, data changes only through validated methods, making code safer.