Access modifiers in Java control the visibility and accessibility of classes, methods, variables, and constructors. They help enforce encapsulation and protect data from unauthorized access.
Access modifiers are written before the class, method, or variable declaration. Only public and default are allowed for top-level classes.
// Demonstrates all four access modifiers in Java
public class AccessDemo {
public int publicVar = 10;
protected int protectedVar = 20;
int defaultVar = 30;
private int privateVar = 40;
public void showValues() {
System.out.println(publicVar);
System.out.println(protectedVar);
System.out.println(defaultVar);
System.out.println(privateVar);
}
}
All variables are accessible inside the same class. However, when accessed from another class or package, visibility depends on the access modifier used.
Click a Scenario to see which modifiers grant access from that location:
Current Context: Inside the class where variable is declared.
protectedprivate members from outside the class