Junior — Middle
Explain the mechanism of the protected access modifier and in which cases it is used.
sobes.tech AI
Answer from AI
The access modifier protected in Java restricts the visibility of class members (fields, methods) so that they are accessible:
- Within the class itself
- In subclasses (even if they are in a different package)
- In other classes of the same package
That is, protected is an intermediate level between private and public.
It is used when you want to provide access to class members for inheritors but hide them from general access outside.
Example:
package example;
public class Parent {
protected int value = 10;
}
package example.sub;
import example.Parent;
public class Child extends Parent {
public void printValue() {
System.out.println(value); // access to protected field
}
}
Here, Child can access value, even though it is not public.