Sobes.tech
Junior — Middle

Kas saaksite selgitada, mida tähendab inkapsulatsioon objektorienteeritud programmeerimises?

sobes.tech AI

Vastus AI-lt

In object-oriented programming, encapsulation is a principle that allows hiding the internal 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, the value can be retrieved or changed, controlling access to the data.