What is encapsulation?
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.