OOP Fundamentals • EncapsulationHard⏱️ ~4 min
Interview Deep Dive: Common Questions
Typical Interview Questions on Encapsulation:
Question 1: "Why not just make all fields private with getters/setters?"
Answer Framework: Distinguish between data structures and objects. Data structures (DTOs, configuration) carry information with no behavior - public fields are fine. Objects encapsulate behavior and protect invariants - use methods that express intent, not mechanical getters/setters.
Example: "For a
UserProfile DTO passed to an API, public fields work. For a BankAccount domain object, I'd have deposit() and withdraw() methods instead of setBalance(), because balance changes represent business operations with rules."Question 2: "Design a Library system. How do you prevent a book from being checked out twice?"
Answer Approach: Focus on the
BookCopy class (each physical copy). Make borrowedBy and dueDate private. Provide checkOut(member) method that validates availability.class BookCopy {
- borrowedBy: Member
- dueDate: Date
+ checkOut(member: Member): Result {
if (this.borrowedBy != null) {
return Result.failure("Already borrowed")
}
this.borrowedBy = member
this.dueDate = now() + 14days
return Result.success()
}
+ returnBook(): void
+ isAvailable(): boolean
}
- borrowedBy: Member
- dueDate: Date
+ checkOut(member: Member): Result {
if (this.borrowedBy != null) {
return Result.failure("Already borrowed")
}
this.borrowedBy = member
this.dueDate = now() + 14days
return Result.success()
}
+ returnBook(): void
+ isAvailable(): boolean
}
Key point:
borrowedBy cannot be set directly. Availability is checked atomically with assignment.Question 3: "How does encapsulation relate to SOLID principles?"
Connection Points:
Single Responsibility: Encapsulation groups related data and behavior. A well-encapsulated class naturally has cohesive responsibilities.
Open/Closed: By hiding implementation behind interfaces, you can extend behavior without modifying client code (protected through encapsulation).
Liskov Substitution: Encapsulation ensures subclasses maintain parent invariants by controlling state access.
Interface Segregation: Public methods (the encapsulated interface) should be minimal and focused.
Dependency Inversion: Encapsulation enables depending on abstractions - clients use public interface, not internal details.
Question 4: "Your code review shows a class with 15 getters and no other methods. What's wrong?"
Diagnosis: This is an anemic domain model - a sign of procedural programming disguised as OOP. The class is a data bag.
Refactoring: Identify where those getters are used. If there's logic like
if (account.getBalance() >= amount) in client code, move that logic into the class as account.canWithdraw(amount). Replace getters with behavior.Exception: If this class is a DTO (Data Transfer Object) for API responses, serialization, or UI binding, then getters-only is correct. The fix is to rename it (e.g.,
AccountDTO or AccountView) to signal its purpose. Domain logic should live in a separate Account domain class.Question 5: "When would you use protected instead of private?"
Answer: Use protected when designing for inheritance and subclasses need to access fields to implement their behavior, but external clients should not.
Example: In a
Vehicle hierarchy, fuelLevel might be protected so Car and Truck subclasses can implement refuel() differently, but external code cannot directly manipulate fuel.Caution: Protected breaks encapsulation across package boundaries. Prefer composition over inheritance when possible, keeping fields private and exposing minimal protected methods.
Interview Tip: Always connect encapsulation to real problems - "Without encapsulation, X can happen, which violates business rule Y". Show you understand the 'why', not just the 'how'.
Machine Coding Checklist:
First, Identify domain entities with invariants (account balance, parking capacity)
Second, Make all fields private by default
Third, Expose behavior through methods named after domain operations
Fourth, Validate inputs in public methods before state changes
Fifth, Use DTOs for data transfer, domain objects for business logic
💡 Key Takeaways
✓Encapsulation prevents double-booking and constraint violations in design
✓Anemic models with only getters/setters indicate missing encapsulation
✓Protected fields enable inheritance while maintaining some encapsulation
✓Encapsulation supports all SOLID principles by hiding implementation
✓Machine coding: make fields private, expose domain operations, validate invariants
📌 Examples
1Library preventing double-checkout through BookCopy encapsulation
2BankAccount exposing deposit/withdraw instead of setBalance
3Vehicle hierarchy using protected for subclass access to fuel