Sobes.tech
Junior — Middle

Can you explain what encapsulation means in object-oriented programming?

sobes.tech AI

Answer from AI

Encapsulation in object-oriented programming is a principle that allows hiding the internal implementation details of an object and providing access to data and methods only through a defined interface. This helps protect the object's state from incorrect usage and makes code maintenance easier.

In C#, encapsulation is achieved using access modifiers (private, protected, public) and properties. For example:

class Person
{
    private string name; // hidden field

    public string Name  // public property for access
    {
        get { return name; }
        set { name = value; }
    }
}

Here, the name field is not directly accessible from outside, but through the Name property, you can get or set the value, controlling access to the data.

Can you explain what encapsulation means in… - sobes.tech