Junior — Middle
Explain the purpose and use of the protected access modifier in object-oriented programming.
sobes.tech AI
Answer from AI
The protected access modifier in object-oriented programming restricts access to class members (fields, methods) so that they are accessible:
- Within the class itself,
- In subclasses,
- Within the same package (in languages that have the concept of packages, such as Java).
This allows hiding implementation details from the outside world while still enabling subclasses to use and override these members.
Example in Java:
public class Animal {
protected void makeSound() {
System.out.println("Some sound");
}
}
public class Dog extends Animal {
@Override
protected void makeSound() {
System.out.println("Bark");
}
}
Here, the makeSound method is accessible within the Dog class but not accessible from other classes that are not subclasses.