Sobes.tech
Junior

How does the 'protected' access modifier work in programming languages?

sobes.tech AI

Answer from AI

Access modifier protected provides access to a class member (field, method, or property) from:

  • The class where it is declared.
  • Subclasses (derived classes).
  • In some languages (e.g., Java), from all classes within the same package.

Applicability by language:

  • Java: Available within the package and in subclasses of any package.
  • C#: Available within the class and subclasses. Also, protected internal provides access within the assembly and in subclasses (including subclasses in other assemblies).
  • C++: Available within the class and subclasses.
  • Python: Does not have strict protected. Members intended for protection are usually named with a single underscore (_), which is a convention, not a strict access restriction.

Example (Java):

class Parent {
    protected int protectedField;

    protected void protectedMethod() {
        // ...
    }
}

class Child extends Parent {
    public void accessProtected() {
        this.protectedField = 10; // Access from subclass
        this.protectedMethod(); // Access from subclass
    }
}

class AnotherClassInSamePackage {
    public void accessProtected(Parent p) {
        p.protectedField = 20; // Access from same package
        p.protectedMethod();   // Access from same package
    }
}

class AnotherClassInDifferentPackage {
    // Cannot access protected members directly
    // unless it is a subclass
}

protected is widely used for inheritance, allowing subclasses to extend parent class functionality while hiding internal details from outside.