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:
- Within the class: Access is allowed.
protectedmembers are visible from anywhere inside their class. - In derived classes: Access is allowed. Classes inheriting from a class with
protectedmembers can directly access these members, even if they are in another package (in some languages, e.g., Java). - Within the same package (in some languages, e.g., Java): Access is allowed, equivalent to
default(package-private).protectedmembers are visible to all classes in the same package, regardless of inheritance. - Outside (other packages, classes that are not inheritors): Access is denied. Direct access to
protectedmembers 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.