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: • public provides unrestricted access from anywhere in the application. • protected allows access within the same package and from subclasses. • default (package-private) restricts access to classes within the same package. • private restricts access to the declaring class only. • Selecting the correct access modifier helps create maintainable and secure applications.

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:

• public → REST API service methods accessible across modules. • protected → Common methods shared by parent and child classes. • default → Internal helper classes within the same package. • private → Sensitive fields such as password, salary, or account balance.

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."