In Java, access modifiers determine the visibility or accessibility of classes, methods, constructors, and variables. They help enforce encapsulation and control how different parts of your code interact.
There are four main access modifiers in Java:
1. public
- Scope: Accessible from anywhere in the program—across all packages.
- Use Case: When you want a class or method to be universally accessible.
- Example:

2. protected
- Scope:
- Accessible within the same package.
- Also accessible in subclasses, even if they are in different packages.
- Use Case: When you want to allow inheritance but still restrict access to outsiders.
- Example:

3. default
(no modifier)
- Scope: Accessible only within the same package.
- Use Case: When you want to hide implementation details from other packages.
- Example:

4. private
- Scope: Accessible only within the same class.
- Use Case: When you want to encapsulate logic or data completely.
- Example:

🔒 Summary Table
Modifier | Same Class | Same Package | Subclass (Other Package) | Other Packages |
---|---|---|---|---|
public | ✅ | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ✅ | ❌ |
default | ✅ | ✅ | ❌ | ❌ |
private | ✅ | ❌ | ❌ | ❌ |