Access modifiers control where a class member can be accessed from.
Java provides four access levels:
privatedefaultprotectedpublicWe will use simple Java files like:
User.java
UserService.java
Admin.java
Main.java
For package-related examples, we can simply mention the package at the top of the file.
privateA private member can only be accessed inside the same class.
User.javaclass User {
private String password = "secret123";
void printPassword() {
System.out.println(password); // ✅ Allowed
}
}
The password variable is accessible inside User.
But another class cannot access it.
Main.javaclass Main {
public static void main(String[] args) {
User user = new User();
System.out.println(user.password); // ❌ Error
}
}
Why?