Sobes.tech
Junior

How does the protected access modifier work in programming languages?

sobes.tech AI

Answer from AI

The protected access modifier defines the visibility level of class members (fields, methods). Access to them is restricted:

  1. Within the class: Access is allowed. protected members are visible from anywhere inside their class.
  2. In derived classes: Access is allowed. Classes inheriting from a class with protected members can directly access these members, even if they are in another package (in some languages, e.g., Java).
  3. Within the same package (in some languages, e.g., Java): Access is allowed, equivalent to default (package-private). protected members are visible to all classes in the same package, regardless of inheritance.
  4. Outside (other packages, classes that are not inheritors): Access is denied. Direct access to protected members from classes that are not inheritors or are not in the same package (Java) is impossible.

Example (Java):

class BaseClass {
    protected int protectedMember = 10;

    protected void protectedMethod() {
        // Access from inside the class is allowed
        System.out.println("Protected method from BaseClass");
    }
}

class DerivedClass extends BaseClass {
    void accessProtected() {
        // Access from a subclass is allowed
        System.out.println(protectedMember);
        protectedMethod();
    }
}

class AnotherClassInSamePackage {
    void accessProtected(BaseClass obj) {
        // In Java, access from another class in the same package is allowed
        System.out.println(obj.protectedMember);
        obj.protectedMethod();
    }
}

class AnotherClassInDifferentPackage {
    // ...
    // Attempting access will result in a compilation error
    // obj.protectedMember;
    // obj.protectedMethod();
}

Thus, protected provides a higher level of encapsulation than public, but lower than private or default, making class members accessible to inheritors and, in some languages, to classes in the same package.