Sobes.tech
Junior

What is encapsulation in object-oriented programming?

sobes.tech AI

Answer from AI

Encapsulation is an object-oriented programming mechanism that binds data (attributes) and methods working with this data into a single object (class), hiding the internal state of the object from the outside world and providing controlled access to its members through a public interface.

Main principles of encapsulation:

  • Data Hiding: The internal implementation details of a class are hidden from external access. The user interacts with it through its public methods without knowing the internal data structure.
  • Access Control: Encapsulation allows controlling how external objects can access and modify data. This is achieved through access specifiers (public, protected, private in other languages, and naming conventions and properties in Python).

Example in Python:

class BankAccount:
    def __init__(self, balance=0):
        # Private attribute, indicated by double underscore
        self.__balance = balance

    def deposit(self, amount):
        # Public method to modify balance
        if amount > 0:
            self.__balance += amount
            print(f"Deposited {amount}. New balance: {self.__balance}")
        else:
            print("Deposit amount must be positive.")

    def withdraw(self, amount):
        # Public method to modify balance
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            print(f"Withdrew {amount}. New balance: {self.__balance}")
        else:
            print("Invalid withdrawal amount or insufficient funds.")

    def get_balance(self):
        # Public method to get the balance value
        return self.__balance

# External code cannot directly access __balance
account = BankAccount(100)
account.deposit(50)
account.withdraw(30)
print(f"Current balance via public method: {account.get_balance()}")

# Attempt to directly access the private attribute (works via name mangling but not recommended)
# print(account.__balance)  # Will raise AttributeError

Advantages of encapsulation:

  • Security: Protects data from unauthorized access and incorrect modifications.
  • Modularity: Allows changing the internal implementation of a class without affecting the code that uses this class, provided the public interface remains the same.
  • Ease of use: The external world interacts with the object through a simple and understandable interface, without delving into complex implementation details.
  • Maintainability: Simplifies debugging and modifying code, as changes are confined within the class.

In Python, the concept of "completely private" members is more based on naming conventions (prefix _ or __). Double underscores (__) use name mangling to simulate "privacy".