Access modifiers are used to control the visibility of classes, methods, variables, and constructors in Java. Choosing the appropriate access modifier helps enforce encapsulation, improve security, and ensure that program components are accessible only where needed.
1. Public Access Modifier
Use when a method or class should be available throughout the application.
A service class exposing business operations to other modules.
public class UserService {
public void createUser() {
System.out.println("User Created");
}
}2. Protected Access Modifier
Use when members should be accessible to subclasses but hidden from unrelated classes.
A parent Employee class exposing common functionality to Manager and Developer subclasses.
protected void calculateSalary() {
System.out.println("Salary Calculated");
}3. Default (Package-Private) Access Modifier
Use when members should be shared only among classes within the same package.
Utility classes used internally within a module.
class ValidationUtil {
void validate() {
System.out.println("Validation Completed");
}
}4. Private Access Modifier
Use for sensitive data and internal implementation details.
Protecting an employee's salary or account balance from direct access.
public class Employee {
private double salary;
public double getSalary() {
return salary;
}
}A concise interview answer is
Use public when access is required from anywhere, protected when access is needed by subclasses, default when access should be limited to the same package, and private when data or methods should remain accessible only within the declaring class.
Last updated: 16 July 2026
Previous question: What are access modifiers in Java?
Next question: Why use getters and setters instead of making fields public?