No when features are friendly or protected they can be accessed from all the
classes in that package but not from classes in another package.
In Java, the protected
and default (package-private or friendly) access modifiers have different levels of visibility.
- Protected Access:
- Members (fields, methods, and nested classes) with the
protected
access modifier are accessible within the same package and also by subclasses, even if they are in different packages. - This means that if a class A has a protected member, a subclass B of A, whether in the same package or a different package, can access that protected member.
- Members (fields, methods, and nested classes) with the
Example:
// File: PackageA/ClassA.java
package PackageA;
public class ClassA {protected int protectedField;
}
// File: PackageB/ClassB.java
package PackageB;
import PackageA.ClassA;
public class ClassB extends ClassA {
public void accessProtectedField() {
int value = protectedField; // Accessing protected field from subclass
}
}
- Default (Package-Private) Access:
- Members with default (package-private or friendly) access modifier are accessible only within the same package.
- If a class A has a default-access member, only other classes in the same package as A can access that member.
Example:
// File: PackageA/ClassA.java
package PackageA;
class ClassA {int defaultField; // Package-private field
}
// File: PackageB/ClassB.java
package PackageB;
// The following code would result in a compilation error because ClassB is in a different package
// and cannot access the defaultField in ClassA.
// public class ClassB {
// public void accessDefaultField() {
// ClassA objA = new ClassA();
// int value = objA.defaultField; // Compilation error
// }
// }
In summary, protected
members can be accessed by subclasses, even if they are in different packages, while default (package-private) members can only be accessed within the same package.