Junior — Middle
Can you explain the basic principles of encapsulation in object-oriented programming?
sobes.tech AI
Answer from AI
Encapsulation is one of the fundamental principles of object-oriented programming, which involves hiding the internal implementation of an object and providing access to data only through specific methods.
Key points:
- Data hiding: internal fields of an object are made private to prevent direct access from outside.
- Controlled access: providing public methods (getters and setters) for reading and modifying the state.
- Data integrity protection: methods can validate input data before changing the state.
Example in Python:
class Person:
def __init__(self, name):
self.__name = name # private field
def get_name(self):
return self.__name
def set_name(self, name):
if isinstance(name, str) and name:
self.__name = name
else:
raise ValueError("Name must be a non-empty string")
p = Person("Ivan")
print(p.get_name()) # Ivan
p.set_name("Peter")
print(p.get_name()) # Peter
Thus, encapsulation helps protect the object from incorrect usage and simplifies code maintenance.