Can you provide examples of when to use each type of access modifier?

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.

Key Points

Example

1. Public Access Modifier

Use when a method or class should be available throughout the application.

Example

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.

Example

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.

Example

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.

Example

Protecting an employee's salary or account balance from direct access.

public class Employee {

    private double salary;

    public double getSalary() {
        return salary;
    }
}

Real-World Scenario

Interview Tip

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?

More Core Java - Level II interview questions

All Core Java - Level II questions