Skip to content

What Is Encapsulation in OOP? Definition and Examples

Quick answer

Encapsulation in OOP explained: what it means, how Java private and Python underscore conventions differ, a bank account example and common mistakes.

What Is Encapsulation in OOP? Definition and Examples

Encapsulation in OOP means bundling an object's data together with the methods that work on it, and controlling how outside code can reach that data. Other code uses a small public interface, while the internal state stays protected. This lets you change the inside later without breaking the code that uses the object.

Key takeaways

  • Encapsulation keeps state and the behaviour that changes it together in one object.
  • Outside code goes through public methods, which can check inputs before changing state.
  • Java enforces access with private; Python relies on naming conventions.
  • It differs from abstraction: encapsulation guards the data, abstraction shows only what a user needs.

On this page:

TermMain ideaEveryday picture
EncapsulationHide and guard state behind methodsThe ledger stays inside the bank
AbstractionShow only what a user needs to knowAn ATM with a few buttons
InheritanceA class reuses another class's featuresA savings account is a kind of account
PolymorphismOne call, different behaviour by typeEach account computes interest its own way

What does encapsulation mean in OOP?

It means an object owns its data and exposes only chosen operations. According to the Oracle Java Tutorials, an object is a software bundle of related state and behaviour, and the lesson on objects introduces the concept of data encapsulation and the benefits of designing software this way.

A plain analogy: an ATM hides the bank's ledger behind a few buttons. You can deposit or withdraw, but you cannot open the ledger and type a new balance.

How does encapsulation work?

You mark the data as non-public and provide methods that enforce the rules. In Java, the Oracle tutorial on controlling access to members says the private modifier specifies that a member can only be accessed in its own class. It advises using the most restrictive access level that makes sense and using private unless you have a good reason not to.

The same idea in Java looks like this (illustrative): a private double balance; field with a public void deposit(double amount) method that rejects an amount that is not greater than 0.

Python works differently. The Python tutorial says private instance variables that cannot be accessed except from inside an object do not exist in Python. A name prefixed with an underscore, such as _spam, should be treated as a non-public part of the API. The tutorial adds that nothing in Python makes it possible to enforce data hiding; it is all based upon convention. Here is a bank account that follows that convention:

class BankAccount:
    def __init__(self, opening_balance=0):
        self._balance = 0
        if opening_balance:
            self.deposit(opening_balance)

    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 balance")
        self._balance -= amount

    @property
    def balance(self):
        return self._balance

acct = BankAccount(500)
acct.deposit(250)
print(acct.balance)   # 750

Callers read balance through a property and change it only through deposit and withdraw, so the public methods cannot leave a negative balance. Setting acct.balance = 1 raises an AttributeError, because the property has no setter. Writing to acct._balance would still work, because the underscore is only a convention.

Python also offers name mangling: an identifier of the form __spam is textually replaced with _classname__spam. The tutorial says the rules are designed mostly to avoid accidents, and that it is still possible to access or modify a variable considered private.

Where is encapsulation used?

It is used in almost every class-based codebase: accounts, carts, orders, payment rules and API clients. An illustrative Indian example: a UPI-style payment class keeps its daily limit private and exposes a pay(amount) method that checks the limit first, so every caller gets the same rule.

The flexibility benefit is real. Oracle says public fields tend to link you to a particular implementation and limit your flexibility in changing your code, and advises avoiding public fields except for constants. Suppose an order class stores items in a list and later moves to a dictionary. Callers using only public methods keep working. This is an illustrative scenario.

What are the common mistakes and confusions?

  • Making every field public. Anyone can then set invalid values, and changing the internals breaks callers.
  • Adding a getter and setter for every field with no checks. That exposes the data without guarding it.
  • Believing Python's underscore is a lock. It is a signal to other developers.
  • Mixing it up with abstraction. Encapsulation protects state; abstraction decides what to show.

Start with an introduction to object-oriented programming and polymorphism. For Java details, see Java data types and variables and primitive vs reference types in Java. Objects often talk through interfaces, see what an API is. For interview practice, try OOPs interview questions and answers.

Next step

Extend the bank account class: add a daily withdrawal limit stored in a non-public attribute, and write a few calls that try to break the rules. Then rewrite the class in Java with private fields and compare how each language protects the state.

Frequently asked questions

What is encapsulation in OOP?

Encapsulation is bundling an object's data with the methods that operate on it and controlling access to that data. Outside code uses public methods, while internal state stays protected and can be validated.

How is encapsulation achieved in Java?

By declaring fields private and exposing public methods. Oracle's tutorial says the private modifier allows access only within the member's own class, and advises using private unless you have a good reason not to.

Does Python have private variables?

Not truly. The Python tutorial says private instance variables inaccessible from outside an object do not exist. A leading underscore marks a name as non-public by convention, and name mangling only helps avoid accidents.

What is the difference between encapsulation and abstraction?

Encapsulation hides and guards an object's state behind methods. Abstraction exposes only what a user needs to know. An ATM hiding the ledger behind buttons shows both ideas at once.

Why is encapsulation useful?

It lets methods validate changes to state and lets you alter the internals later. Oracle notes public fields tie you to a particular implementation and limit flexibility in changing your code.

Share LinkedIn X WhatsApp
×

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.