What are access modifiers?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex OOP Concepts topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
Access modifiers control the visibility and accessibility of classes, methods, and fields. They are the primary mechanism for enforcing encapsulation. Java's four access levels (most to least restrictive): (1) private: accessible only within the same class. Not accessible from subclasses or other classes: private double balance; // Only BankAccount can access private void updateLedger() {}; (2) package-private (default, no keyword): accessible within the same package — the default when no modifier is specified: double interestRate; // Any class in same package void calculateInterest() {}; (3) protected: accessible within the same package AND by subclasses (even in different packages): protected String ownerName; // Accessible by subclasses protected void sendAlert() {}; (4) public: accessible from anywhere — any class in any package: public String getAccountNumber() { return accountNumber; } public void deposit(double amount) {}. Visibility matrix: private < default (package) < protected < public. Best practices: fields should almost always be private; getters/setters can be public if needed; helper methods should be private; constructor visibility depends on design (private for Singleton, public for normal, protected for abstract). Other OOP languages: C# has internal (assembly-wide), protected internal; Swift has fileprivate, internal (module); Python uses naming convention (_single = protected, __double = private via name mangling — not enforced).
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex OOP Concepts answers easy to follow.