Loading lessons...
Java Modifiers
Java Modifiers
Modifiers control how classes, methods, and attributes can be accessed or changed.
Access modifiers
| Modifier | Effect |
|---|---|
public | Accessible everywhere |
private | Accessible only inside the class |
default (no keyword) | Accessible in the same package |
protected | Accessible in the same package and subclasses |
Non-access modifiers
| Modifier | Effect |
|---|---|
final | Cannot be changed or extended |
static | Belongs to the class, not objects |
abstract | Cannot create objects; must be inherited |
Final example
final class Vehicle {
// a final class cannot be inherited
}
Private example
public class Main {
private int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
// myObj.x is NOT accessible here from outside
}
}
Choosing modifiers
- Use
privatefor internal data to protect it. - Use
publicfor things other code should use. - Use
finalto prevent changes.
TL;DR
- Access modifiers:
public,private,protected, default. - Non-access modifiers:
final,static,abstract. privatemembers are only visible inside their class.