Junior — Middle
Can you explain the concept of encapsulation in object-oriented programming?
sobes.tech AI
Answer from AI
Encapsulation is a principle of object-oriented programming that involves combining data (variables) and methods that operate on this data within a single object (class). The implementation details are hidden from the outside world, and access to the data is provided through public methods.
This allows:
- Protecting the internal state of an object from incorrect usage.
- Changing the internal implementation without affecting the code that uses the object.
Example in Python:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private attribute
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
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # 150
# account.__balance # Error, access is forbidden
Here, the attribute __balance is hidden from direct access, and interaction with it occurs through class methods.