Java Modifiers
🔹 Java Modifiers
Modifiers in Java are keywords that change the behavior of classes, methods, and variables. They define access level, scope, and other properties.
There are two main types:
-
Access Modifiers – Control visibility.
-
Non-Access Modifiers – Provide other properties like
final,static, etc.
✅ 1. Access Modifiers
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| public | ✅ | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ✅ | ❌ |
| default (no modifier) | ✅ | ✅ | ❌ | ❌ |
| private | ✅ | ❌ | ❌ | ❌ |
-
public → Accessible everywhere.
-
protected → Accessible in same package & subclasses.
-
default → Accessible only within same package.
-
private → Accessible only within the class.
Example: Access Modifiers for Variables
✅ 2. Non-Access Modifiers
| Modifier | Description |
|---|---|
| final | Cannot be changed (variable), cannot be overridden (method), cannot be inherited (class) |
| static | Belongs to class rather than object |
| abstract | Must be implemented in subclass (for classes and methods) |
| synchronized | Used for thread safety in methods |
| volatile | Variable value can be changed by multiple threads |
| transient | Variable not serialized |
| native | Method implemented in native code (C/C++) |
Examples
a) final Variable
b) static Variable
c) abstract Class
✅ 3. Key Points
-
Access modifiers control visibility.
-
Non-access modifiers control behavior, inheritance, and memory.
-
Modifiers can be combined (e.g.,
public static final int MAX = 100;). -
Always choose modifiers for encapsulation, security, and clarity.
