Encapsulation - Rybd04/2143-OOP GitHub Wiki

Definition

Encapsulation

It refers to the bundling of data and the methods that operate on that data into a single unit, typically a class. It also involves restricting direct access to some components of an object, which is a form of data hiding.

Explanation

Basically encapsulation is the hiding of data. Encapsulation requires all interaction with an object be performed with methods.

Basic Code Example

class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance  # private variable (name mangled)

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

    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount

    def get_balance(self):
        return self.__balance

balance is encapsulated — it can't be accessed directly from outside.

The account’s balance can only be modified through controlled methods (deposit, withdraw).

This protects the balance from being set to a negative or invalid value directly.

Image

image

Additional Resources

https://www.geeksforgeeks.org/encapsulation-in-java/ https://www.sumologic.com/glossary/encapsulation/