Lesson 16 — Object-Oriented Programming

Encapsulation

Encapsulation bundles data with the methods that operate on it, and restricts direct access to that data from outside the class, protecting an object from being put into an invalid state.

Getters and Setters

Rather than exposing member variables directly as public, encapsulation keeps them private and provides public methods to read (getter) and write (setter) them. A setter can validate a value before accepting it, something a plain public variable can never do.

C++ — Encapsulated class
class BankAccount {
private:
    double balance;

public:
    BankAccount(double startingBalance) {
        balance = startingBalance;
    }

    double getBalance() {
        return balance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    bool withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }
        return false; // reject invalid withdrawal
    }
};

Common Mistakes

  • Making member variables public "for convenience", which removes any control over how they are changed.
  • Writing a setter that blindly accepts any value without validation, defeating the purpose of encapsulation.
  • Exposing a getter that returns a reference to internal mutable data, allowing outside code to bypass validation entirely.
  • Confusing encapsulation (data hiding) with abstraction (hiding implementation complexity) — they are related but distinct concepts.

Professional Tip

A good rule of thumb: if changing a class's internal data representation would break code outside the class, that data isn't properly encapsulated. Well-encapsulated classes can change their internals freely as long as the public interface stays the same.

Your Turn

Extend the BankAccount class with a private transaction count that increases every time deposit() or withdraw() succeeds, and a public getTransactionCount() method to read it. There should be no way to modify the count directly from outside the class.

Mini Quiz

What is the main purpose of making member variables private and exposing getters/setters?