What is encapsulation?
Why Interviewers Ask This
This is a classic screening question for OOP Concepts roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
Encapsulation is the bundling of data (attributes) and the methods that operate on that data within a single unit (class), and restricting direct access to some of the object's components. It hides the internal state and requires all interaction to occur through well-defined interfaces (public methods). Information hiding: internal implementation details are hidden from outside. External code sees only what's necessary (the public interface). Example (Java): public class Temperature { private double celsius; // Hidden -- can't access directly from outside // Controlled access via methods: public void setCelsius(double temp) { if (temp < -273.15) { // Absolute zero validation throw new IllegalArgumentException("Temperature below absolute zero!"); } this.celsius = temp; } public double getCelsius() { return celsius; } public double getFahrenheit() { // Derived property -- not stored return celsius * 9.0/5.0 + 32; } }. Benefits of encapsulation: (1) Data protection: prevents invalid state — validation in setters ensures invariants are maintained; (2) Flexibility: can change internal representation without affecting users of the class; (3) Reduced complexity: users don't need to understand implementation; (4) Easier maintenance: changes are localized within the class. Access modifiers for encapsulation: private (class only), protected (class + subclasses), package-private/internal (same package/module), public (everywhere). Getter/setter (accessor/mutator) pattern: private fields + public getters (and optionally setters). Avoid "anemic" classes that are just bags of getters/setters — put behavior where the data is.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a OOP Concepts codebase.