Chapter 05 of 26

Encapsulation

A medicine capsule keeps the powder inside a shell. You swallow the capsule as one unit; you do not handle the chemicals directly, and the shell protects them until they reach the right place. An ATM works the same way: the cash is locked inside, and the only way to get it is through the keypad and screen, which check your PIN and balance first.

This is exactly the idea of encapsulation, the first of the four pillars introduced in Introduction to OOP. In this chapter we will see what goes wrong without it, how to encapsulate a class properly in Java, the subtle ways encapsulation leaks, immutable objects and records, and how C++ and Python approach the same idea.


What Is Encapsulation?

Encapsulation is the bundling of data and the methods that operate on that data into a single unit (a class), together with restricting direct access to the object's internal state so that it can be read or changed only through the class's own methods.

So encapsulation has two parts:

  1. Bundling: data and the code that works on it live together in one class.

  2. Data hiding (information hiding): the internal data is not directly reachable from outside; the class exposes a controlled set of operations instead.

The goal is not secrecy for its own sake. The goal is that an object is always responsible for keeping its own data valid. The rules that must always hold for an object's data are called its invariants, for example "balance is never negative" or "marks are between 0 and 100".


The Problem: A Class With No Protection

class BankAccount {
    String owner;
    double balance;          // anyone can touch this
}

class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        acc.owner = "Nikhil";
        acc.balance = 1000;

        acc.balance = acc.balance - 5000;   // withdraw more than we have
        acc.owner = "";                     // an account with no owner

        System.out.println("Owner: '" + acc.owner + "', balance: " + acc.balance);
    }
}

Output:

Owner: '', balance: -4000.0

The program compiles and runs, and silently produces nonsense: an account with no owner and a balance of −4000. Worse, the code that broke the account could be in any file of a large project. When a bug report arrives, you have to search the whole codebase for every line that writes to balance.


The Solution: An Encapsulated Class

class BankAccount {
    private final String accountNumber;
    private final String owner;
    private double balance;
    private int transactions;

    BankAccount(String accountNumber, String owner, double openingBalance) {
        if (owner == null || owner.isBlank()) {
            throw new IllegalArgumentException("owner is required");
        }
        if (openingBalance < 0) {
            throw new IllegalArgumentException("opening balance cannot be negative");
        }
        this.accountNumber = accountNumber;
        this.owner = owner;
        this.balance = openingBalance;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("deposit must be positive");
        }
        balance += amount;
        transactions++;
    }

    public void withdraw(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("withdrawal must be positive");
        }
        if (amount > balance) {
            throw new IllegalStateException("insufficient balance");
        }
        balance -= amount;
        transactions++;
    }

    public double getBalance()      { return balance; }
    public String getOwner()        { return owner; }
    public int getTransactions()    { return transactions; }

    // last 4 digits only: the full number never leaves the object
    public String getMaskedNumber() {
        return "XXXX" + accountNumber.substring(accountNumber.length() - 4);
    }
}

class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount("50100234567812", "Nikhil", 1000);

        acc.deposit(500);
        try {
            acc.withdraw(5000);
        } catch (IllegalStateException e) {
            System.out.println("Withdraw failed: " + e.getMessage());
        }
        acc.withdraw(300);

        System.out.println(acc.getOwner() + " " + acc.getMaskedNumber());
        System.out.println("Balance: " + acc.getBalance());
        System.out.println("Transactions: " + acc.getTransactions());

        // acc.balance = 1_000_000;   // compile error: balance has private access
    }
}

Output:

Withdraw failed: insufficient balance
Nikhil XXXX7812
Balance: 1200.0
Transactions: 2

If we uncomment the last line in main, the compiler refuses:

Main.java:64: error: balance has private access in BankAccount
        acc.balance = 1_000_000;   // compile error: balance has private access
           ^
1 error

What did we do?

  • All fields are private. Only code inside BankAccount can touch them.

  • The constructor validates, so an invalid account cannot even be created (see Constructors & Destructors).

  • Changes go through meaningful operations (deposit, withdraw) that enforce the rules and also update the transaction count. Two related pieces of data can never get out of sync.

  • There is no setBalance(). A bank account's balance should change only through deposits and withdrawals, so we simply do not offer a way to set it directly.

  • accountNumber and owner are final: once set in the constructor, they never change.

  • Hidden data stays hidden. getMaskedNumber() reveals only the last four digits; the full number never leaves the object.

Now, if the balance is ever wrong, there are only two methods to check. That is the practical power of encapsulation.


How to Encapsulate a Class in Java

  1. Make fields private.

  2. Initialise and validate them in the constructor.

  3. Provide public methods for the operations the outside world needs, not for every field.

  4. Provide getters only for data that others genuinely need to read.

  5. Provide setters only when changing that value directly makes sense, and validate inside them.

  6. Make fields final wherever the value should never change.

  7. Never hand out references to internal mutable objects (explained below).

A quick reminder of Java's access levels (full details in Access Modifiers):

Modifier

Visible to

Typical use

private

Same class only

Fields, internal helper methods

(none) package-private

Same package

Classes and methods internal to a module

protected

Same package + subclasses

Hooks meant for subclasses

public

Everyone

The class's intended operations


Getters and Setters: Use With Thought

The usual Java naming convention is getX() for reading, isX() for boolean values, and setX(value) for writing:

public int getAge() { return age; }

public void setAge(int age) {
    if (age < 0 || age > 150) {
        throw new IllegalArgumentException("invalid age: " + age);
    }
    this.age = age;
}

Even a simple getter/setter pair is better than a public field, because you can later add validation, logging or a change in internal representation without changing any caller.

But "private field + public getter + public setter for everything" is not real encapsulation. If every field has an unchecked setter, the object is just a public data bag with extra typing. Prefer methods that express intent:

Weak (data-oriented)

Better (behaviour-oriented)

acc.setBalance(acc.getBalance() - 500)

acc.withdraw(500)

order.setStatus("CANCELLED")

order.cancel() (which can refuse if already shipped)

if (light.getState() == OFF) light.setState(ON)

light.turnOn()

This guideline is often summarised as "Tell, don't ask": tell an object what to do, instead of asking for its data and making the decision yourself outside it.


Leaky Encapsulation: Returning Internal Objects

Making fields private is not enough if a getter hands out a reference to a mutable internal object.

import java.util.ArrayList;
import java.util.List;

class Course {
    private final String name;
    private final List<String> students = new ArrayList<>();
    private static final int CAPACITY = 2;

    Course(String name) { this.name = name; }

    public void enroll(String student) {
        if (students.size() >= CAPACITY) {
            throw new IllegalStateException(name + " is full");
        }
        students.add(student);
    }

    // LEAKY: hands out the internal list itself
    public List<String> getStudentsLeaky() {
        return students;
    }

    // SAFE: hands out a read-only snapshot
    public List<String> getStudents() {
        return List.copyOf(students);
    }
}

class Main {
    public static void main(String[] args) {
        Course c = new Course("DBMS");
        c.enroll("Ananya");
        c.enroll("Rahul");

        c.getStudentsLeaky().add("Intruder");      // bypasses enroll() and CAPACITY
        System.out.println("After leak: " + c.getStudents());

        try {
            c.getStudents().add("Another");
        } catch (UnsupportedOperationException e) {
            System.out.println("Safe getter blocked the change: " + e.getClass().getSimpleName());
        }
    }
}

Output:

After leak: [Ananya, Rahul, Intruder]
Safe getter blocked the change: UnsupportedOperationException

The course has a capacity of 2, yet it ended up with three students. The field students is private and even final, but getStudentsLeaky() returned the actual list, and the caller modified it directly, skipping enroll() and its capacity check. (final only stops the field from pointing to a different list; it does not freeze the list itself.)

Two standard fixes:

  • Return a copy or a read-only view: List.copyOf(students) (Java 10+) returns an unmodifiable copy; Collections.unmodifiableList(students) returns a read-only view that still reflects later changes.

  • Copy on the way in too: if a constructor receives a list or array from outside, store a copy, otherwise the caller still holds a reference to your internal data.

The same applies to arrays and to mutable types like java.util.Date. Immutable types such as String, Integer and LocalDate are safe to return directly. The difference between copying a reference, a shallow copy and a deep copy is covered in Shallow Copy vs Deep Copy.


The Strongest Encapsulation: Immutable Objects

An immutable object cannot change after it is constructed. If it was valid at birth, it stays valid forever, and it can be shared freely, even between threads, without any locking. String is the most famous example.

Classic recipe for an immutable class in Java:

  • Make all fields private final.

  • Provide no setters or other mutating methods.

  • Validate everything in the constructor.

  • Make defensive copies of any mutable inputs and outputs.

  • Prevent subclasses from breaking the rules (declare the class final).

Records (Java 16+)

For simple data carriers, Java records do most of this for you. A record's fields are automatically private final, it gets a constructor, accessor methods, equals(), hashCode() and toString(), and the record class is implicitly final.

record Marks(String subject, int score) {
    Marks {                                   // compact constructor: validation
        if (score < 0 || score > 100) {
            throw new IllegalArgumentException("score must be 0-100");
        }
    }

    String grade() {
        return score >= 90 ? "A" : score >= 75 ? "B" : score >= 40 ? "C" : "F";
    }
}

class Main {
    public static void main(String[] args) {
        Marks m = new Marks("OOP", 88);
        System.out.println(m + " grade " + m.grade());
        System.out.println(m.subject() + " " + m.score());

        try {
            new Marks("OOP", 120);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}

Output:

Marks[subject=OOP, score=88] grade B
OOP 88
Rejected: score must be 0-100

Note that the accessors are named subject() and score(), not getSubject(). A record is shallowly immutable: if a component is a mutable object such as a List, you should still copy it in the compact constructor.


Encapsulation in C++ and Python

C++

C++ has the same three access specifiers, private, protected and public, written as labels that apply to all following members. As we saw in Classes & Objects, members of a class are private by default and members of a struct are public by default.

C++ also has friend: a class can declare a specific function or class as its friend, giving it access to private members. It is a deliberate, controlled exception (commonly used for operator overloading like operator<<), but every friend weakens encapsulation, so use it sparingly.

Python

Python does not enforce privacy. It relies on conventions and a little help from the language:

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = 0          # double underscore: name mangling
        self.deposit(balance)

    @property
    def balance(self):              # read like a field, but it is a method
        return self.__balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self.__balance += amount


acc = BankAccount("Nikhil", 1000)
acc.deposit(500)
print(acc.balance)

try:
    acc.balance = 99
except AttributeError as e:
    print("AttributeError:", e)

try:
    print(acc.__balance)
except AttributeError as e:
    print("AttributeError:", e)

print(acc._BankAccount__balance)    # still reachable: Python trusts programmers

Output (Python 3.14):

1500
AttributeError: property 'balance' of 'BankAccount' object has no setter
AttributeError: 'BankAccount' object has no attribute '__balance'
1500
  • A single underscore (_balance) means "internal, please don't touch". It is purely a convention.

  • A double underscore (__balance) triggers name mangling: inside the class it is renamed to _BankAccount__balance. This mainly prevents accidental clashes in subclasses; it is not real security, as the last line shows.

  • @property lets you expose a read-only attribute (or add validation in a setter) while callers still write acc.balance.

Python's philosophy is often summarised as "we are all consenting adults here": the language marks what is internal and trusts programmers to respect it.


Encapsulation vs Data Hiding vs Abstraction

These three are frequently confused in exams.

Basis

Encapsulation

Data hiding

Abstraction

Core idea

Bundle data + methods into one unit and control access

Prevent direct outside access to internal data

Expose only essential features, hide implementation complexity

Question it answers

"Where does this data and its logic live, and who may change it?"

"Who can see this field?"

"What does the user of this class need to know?"

Level

Implementation / class level

Part of encapsulation

Design / interface level

Achieved by (Java)

Classes, private fields, public methods

private (and other access modifiers)

Abstract classes, interfaces, well-chosen public methods

ATM example

Cash and logic sealed inside one machine

You cannot reach the cash tray

You see "Withdraw", not the network protocol to the bank

In short: abstraction decides what to show; encapsulation decides how to protect what is hidden. The next chapter, Abstraction, explores the other side.


Benefits of Encapsulation

  • Validity: objects enforce their own invariants, so invalid states cannot occur.

  • Easier debugging: only the class's own methods can change its data, so there are few places to look.

  • Freedom to change internals: you can switch from double to BigDecimal, or from an array to a List, without breaking any code outside the class, as long as the public methods stay the same.

  • Read-only and write-only control: offer a getter without a setter, or vice versa.

  • Safer sharing: immutable, well-encapsulated objects can be shared across code and threads.

  • Lower coupling: other classes depend on what an object does, not how it stores data (see Coupling & Cohesion).


Common Mistakes Students Make

  • Auto-generating a getter and setter for every field without validation, which gives the look of encapsulation without the protection.

  • Returning internal mutable objects (lists, arrays, Date) from getters.

  • Thinking final makes an object immutable. A final reference cannot be re-pointed, but the object it points to can still change.

  • Validating in the setter but not in the constructor (or vice versa). Chain the constructor through the same validation.

  • Saying encapsulation = data hiding. Data hiding is one part; bundling data with its behaviour is the other.

  • Thinking Python's __name makes data private. It only mangles the name.


Interview / Exam Questions

1. What is encapsulation? How is it achieved in Java?

Encapsulation is bundling data and the methods that act on it into a class while restricting direct access to the data. In Java: declare fields private, validate in constructors, and expose public methods (operations and, where needed, getters/setters) that enforce the class's rules.

2. Is a class with private fields and public getters and setters for all of them well encapsulated?

Not necessarily. If the setters do no validation and allow any change, the object's invariants are still unprotected; it is only syntactically encapsulated. Good encapsulation exposes meaningful operations and only the accessors that are really needed.

3. Difference between encapsulation and abstraction?

Abstraction is about exposing only the essential behaviour and hiding complexity (a design-level concern: what a class offers). Encapsulation is about bundling data with its methods and protecting the internal state (an implementation-level concern: how the internals are protected).

4. A class has private final List<String> items and a getter return items;. Is it safe?

No. Callers receive the internal list and can add or remove elements, bypassing the class. Return List.copyOf(items) or Collections.unmodifiableList(items), and copy incoming lists in the constructor.

5. How do you make a class immutable in Java?

Make the class final, make all fields private final, set them only in the constructor after validation, provide no mutators, and make defensive copies of mutable components on the way in and out. For simple data holders, a record does most of this automatically.

6. Does a friend function break encapsulation in C++?

It deliberately relaxes it for one named function or class. Because the class itself chooses its friends, it is a controlled exception rather than a free-for-all, but too many friends defeat the purpose of private members.

7. Can you access a private field from outside the class in Java at all?

Not through normal code; the compiler reports "has private access". Reflection (setAccessible(true)) can bypass it in some cases, though the module system (Java 9+) restricts this across modules. Access modifiers protect against accidental misuse and enforce design, not against a determined attacker running code in your process.


Summary

  • Encapsulation = bundling data with the methods that operate on it + hiding the data behind those methods.

  • Its purpose is to let each object protect its own invariants.

  • In Java: private fields, validating constructors, intent-revealing public methods, and getters/setters only where they make sense.

  • Watch out for leaks: never return internal mutable objects; copy them on the way in and out.

  • Immutable classes and Java records are the strongest form of encapsulation.

  • C++ uses access specifiers plus friend; Python relies on conventions, name mangling and @property.

Next, in Abstraction, we will look at the other side of the coin: deciding what a class should show to the outside world in the first place.