Junior — Middle
Какое отличие между модификаторами доступа package-private и protected в Java?
sobes.tech AI
Answer from AI
In Java, access modifiers package-private (absence of explicit modifier) and protected differ in scope:
-
package-private (default when no modifier is specified):
- Accessible only within the same package.
- Classes from other packages do not see this member.
-
protected:
- Accessible within the same package (like package-private).
- Additionally accessible in subclasses, even if they are in different packages.
Thus, protected extends the scope compared to package-private, allowing subclasses in other packages to access protected members.
Example:
package pkg1;
public class A {
int packagePrivateVar; // package-private
protected int protectedVar;
}
package pkg2;
import pkg1.A;
public class B extends A {
void method() {
// packagePrivateVar is not accessible because B is in another package
// protectedVar is accessible because B is a subclass of A
int x = protectedVar;
}
}