Access modifiers¶
Public¶
Keyword: public
Access: Accessible from anywhere (inside/outside the class, package, or project).
Usage: Typically used for classes, methods, and variables that need global access.
Example
Private¶
Keyword: private
Access: Accessible only within the same class.
Usage: Used to hide class fields or methods, following the principle of encapsulation.
Example
Protected¶
Keyword: protected
Access: Accessible within the same package and by subclasses (even if outside the package).
Usage: Useful when extending classes across packages.
Example
Note
If accessed by a subclass in a different package, it must be through inheritance (not directly via an instance).
Package-Private¶
Keyword: No keyword (Default Access)
Access: Accessible only within the same package.
Usage: Used for classes and members that don’t need to be accessed outside their package.
Example
Note
Package-private is the default if no modifier is specified.
Access Summary¶
Modifier | Same Class | Same Package | Subclass (Different Package) | Other Packages |
---|---|---|---|---|
public |
✅ | ✅ | ✅ | ✅ |
protected |
✅ | ✅ | ✅ (via inheritance) | ❌ |
(default) | ✅ | ✅ | ❌ | ❌ |
private |
✅ | ❌ | ❌ | ❌ |