Menu
Coddy logo textTech

What Is Encapsulation?

In object-oriented programming, encapsulation is keeping an object's data and the methods that work on that data together in one unit, usually a class, and hiding the internal details so other code can use the object only through its public methods.

By Kevin Spektor, Co-founder & CTO

Updated September 24, 2026

Suppose a banking app stores each account's balance in a plain variable. Any line anywhere in the program can write account.balance = -500, and nothing stops it. When a negative balance shows up in production, you have to search the whole codebase for every place that touched it. Encapsulation fixes this: the balance can only change through a few methods, and those methods enforce the rules, for example that a withdrawal may never exceed the balance.

How encapsulation works

Encapsulation combines two ideas:

  1. Bundling. The data (the balance) and the code that works on it (deposit, withdraw) live in the same class.
  2. Hiding. Other code sees only the class's public interface. The data behind it is internal, so it can change only in the ways the class allows.

The rule the class protects is called an invariant: here, "the balance is never negative". Because every change passes through the class's methods, the invariant holds no matter what the rest of the program does.

70
refused: not enough money

Outside code can read acct.balance, but the property has no setter, so acct.balance = 1000 raises an AttributeError. If the balance is ever wrong, there are exactly two methods to inspect.

Encapsulation in Python

Python has no private keyword. It relies on naming conventions that every Python programmer knows:

  • name: public, part of the interface.
  • _name: internal. Nothing stops you from reading it, but the leading underscore says "do not depend on this".
  • __name: Python renames it inside the class (name mangling), so a subclass cannot overwrite it by accident.
  • @property: turns a method into something that reads like an attribute, so you can add checks later without changing any calling code.
0
False
42

Name mangling prevents accidents, not access: the mangled name still works. Python trusts programmers to respect the underscore. In practice most Python code uses a single underscore plus @property, and saves double underscores for classes meant to be subclassed. More on writing classes is in the Python classes docs.

Encapsulation in Java, C++ and JavaScript

Other languages enforce the hiding. In Java, a private field can only be used inside its own class:

public class BankAccount {
    private int balance;  // hidden from every other class

    public int getBalance() { return balance; }

    public void withdraw(int amount) {
        if (amount > balance) throw new IllegalArgumentException("not enough money");
        balance -= amount;
    }
}

Writing account.balance = 1000; in another class does not compile: javac reports balance has private access in BankAccount.

LanguageHidden memberPublic memberEnforced by
Python_name, __namenameConvention
Javaprivate int namepublic int nameThe compiler
C++private: sectionpublic: sectionThe compiler
JavaScript#namenameThe JavaScript engine

C++ makes class members private by default and struct members public. JavaScript's # private fields, added in ES2022, cannot be read from outside the class at all. The docs cover each: Java access modifiers, C++ access specifiers and JavaScript private fields.

Why encapsulation matters

  • Rules live in one place. The check "no withdrawal above the balance" is written once, inside withdraw, instead of before every withdrawal in the program.
  • You can change the inside freely. If you decide to store money as whole cents instead of a float, only the class changes. Code that calls deposit(100) keeps working.
  • Easier debugging. When a value is wrong, the suspects are the few methods allowed to change it, not every line in the program.
  • Less to learn and test. A class with three public methods can be understood and tested through those three methods.

Encapsulation also works above the level of classes. A module that exposes two functions and keeps ten helpers internal is encapsulated in the same way, and so is an operating system that lets programs open files only through system calls.

It is often confused with abstraction. Abstraction decides what the interface offers; encapsulation protects the data behind it. The abstraction page has a full side-by-side comparison. Together with polymorphism and inheritance, they are the four pillars of object-oriented programming.

Common mistakes

  • A getter and a setter for every field. A setBalance that accepts any number protects nothing. Offer the operations the object needs (withdraw), not raw access to each field.
  • Returning internal objects. A method that returns self._items hands the caller the real list, which it can now change. Return a copy or a tuple instead.
  • Treating private as security. Access modifiers prevent mistakes, not attacks. Java code can read private fields through reflection, and Python code can read _name directly. Passwords and keys need real protection, such as hashing and encryption.

Where to go next

Read abstraction next, which covers the difference between the two ideas, then polymorphism. The Python course builds classes step by step, and the Java course shows encapsulation enforced by the compiler.

Frequently Asked Questions

What is encapsulation in simple terms?
Encapsulation means an object keeps its data to itself and offers a few safe ways to use it. A bank account object does not let you type in a new balance; it gives you deposit and withdraw, which check the rules first. The name comes from a capsule, a shell that keeps its contents inside.
What are examples of encapsulation?
A bank account class that allows changes only through deposit and withdraw is the classic example. Python's own list is another: you call append and never manage the memory that stores the items. A module that exposes a few functions and keeps its helper functions private is encapsulation at a larger scale.
What are the three types of encapsulation?
Tutorials that list three types usually mean member variable encapsulation (private fields), function encapsulation (private helper methods) and class encapsulation (a class hidden inside another class or module). These are not formal categories; they are the same idea applied to fields, methods and whole classes.
What is encapsulation in C++ and how is it used?
In C++, you mark data members private and provide public member functions that read or change them. Members of a class are private by default, while members of a struct are public by default. The compiler rejects any code outside the class that tries to use a private member.
What does encapsulation mean in networking?
In networking, encapsulation means wrapping data in the headers of each protocol layer on its way out: an HTTP message goes inside a TCP segment, which goes inside an IP packet, which goes inside an Ethernet frame. It shares the name with the programming idea but is a different concept.
Coddy programming languages illustration

Learn to code with Coddy

GET STARTED