[!INDEX]
- Access Modifiers and Their Priority
- Summary of Access Modifiers
- Example
- Conclusion
1 - Access Modifiers and Their Priority
[!NOTE]
- public
- Visibility: Accessible from any other class or package.
- Use Case: When you want a class, method, or field to be accessible from anywhere in your application.
- protected ( using extends and class object & using import with object in different package)
- Visibility: Accessible within the same package and by subclasses (even if they are in different packages).
- Use Case: When you want to allow access to subclasses and other classes in the same package but restrict access from non-subclasses in other packages.
- Package-Private -default, no modifier ( only package)
- Visibility: Accessible only within the same package. No access modifier is specified.
- Use Case: When you want to restrict access to classes, methods, or fields to other classes in the same package but not expose them to classes outside the package.
- private ( only class , not even subclass)
- Visibility: Accessible only within the class in which it is declared.
- Use Case: When you want to restrict access to members of a class to only that class, hiding implementation details from other classes.
2 - Summary of Access Modifiers
| Modifier | Same Class | Same Package | Subclass (Different Package) | Other Packages |
|---|---|---|---|---|
| public | Yes | Yes | Yes | Yes |
| protected | Yes | Yes | Yes | No |
| Package-Private (default) | Yes | Yes | No | No |
| private | Yes | No | No | No |
3 - Example
// In the same package
public class Example {
public int publicField = 1;
protected int protectedField = 2;
int packagePrivateField = 3; // No modifier
private int privateField = 4;
}
class Test {
public static void main(String[] args) {
Example ex = new Example();
System.out.println(ex.publicField); // Accessible
System.out.println(ex.protectedField); // Accessible
System.out.println(ex.packagePrivateField); // Accessible
System.out.println(ex.privateField); // Not Accessible
}
}
[!NOTE] If you move Test to a different package, public Field and protected Field will remain accessible if Test is a subclass, but package Private Field and private Field will not be accessible.
4. Conclusion
[!NOTE]
Understanding the priority of access modifiers helps you design your classes with appropriate levels of visibility, encapsulation, and access control, ensuring that your code is secure, maintainable, and adheres to object-oriented principles.