Sobes.tech
Junior — Middle

Milline on erinevus private ja protected juurdepääsumeetodite vahel objektorienteeritud programmeerimises?

sobes.tech AI

Vastus AI-lt

In object-oriented programming (using C# as an example), access modifiers private and protected differ in the level of visibility of class members:

  • private — the class member is accessible only within the class itself. Neither subclasses nor other classes can access it.

  • protected — the class member is accessible within the class itself and in all its subclasses (heirs), even if they are in a different namespace.

Example:

class BaseClass
{
    private int privateField = 1;
    protected int protectedField = 2;

    void Show()
    {
        Console.WriteLine(privateField);   // Accessible
        Console.WriteLine(protectedField); // Accessible
    }
}

class DerivedClass : BaseClass
{
    void ShowDerived()
    {
        // Console.WriteLine(privateField); // Error: privateField not accessible
        Console.WriteLine(protectedField);  // Accessible
    }
}

Thus, protected extends the scope of visibility compared to private, allowing inheritors to work with the protected members of the base class.