Junior — Middle
Can you explain the principle of encapsulation in object-oriented programming?
sobes.tech AI
Answer from AI
The principle of encapsulation in object-oriented programming is about hiding the internal implementation of an object and providing access to the object's data and behavior only through specific methods (interface). This helps protect the object's state from incorrect use and external modifications.
For example, in C#, class fields can be made private, and access to them can be organized through public methods or properties:
class Person
{
private string name; // hidden field
public string Name // public property for access
{
get { return name; }
set { name = value; }
}
}
Thus, internal data is protected, and interaction with them is controlled through class methods.