Understanding Encapsulation in Programming

What is Encapsulation?

Encapsulation is one of the core concepts in object-oriented programming. It refers to the bundling of data (variables) and methods (functions) that operate on that data into a single unit — a class. Moreover, encapsulation allows for restricting direct access to some of an object’s components, which means hiding the internal state and requiring all interaction to happen through methods.

Why is Encapsulation Important?

  • Improves code modularity.
  • Enhances security by hiding internal state.
  • Makes maintenance and debugging easier.
  • Prevents external code from corrupting object state accidentally.

Analogy

Think of a capsule pill. The outer shell hides the ingredients inside. Similarly, in programming, encapsulation hides the inner workings of an object and only exposes what is necessary.

Example 1: Encapsulating Data with Access Methods

Let’s define a class called BankAccount. We’ll keep the balance private and only allow deposits and withdrawals through defined methods.

CLASS BankAccount:
    PRIVATE balance

    METHOD constructor(initialAmount):
        SET balance = initialAmount

    METHOD deposit(amount):
        IF amount > 0 THEN
            balance = balance + amount

    METHOD withdraw(amount):
        IF amount <= balance THEN
            balance = balance - amount

    METHOD getBalance():
        RETURN balance
Balance cannot be accessed directly.
Use getBalance() to retrieve current balance.

Explanation:

In the above example:

  • The balance variable is marked as PRIVATE, meaning it can't be accessed from outside the class.
  • To interact with balance, we provide public methods like deposit(), withdraw(), and getBalance().
  • This protects the internal state of the object from unintended changes.

Beginner's Question:

Q: Why not just make the balance variable public and update it directly?

A: If balance is public, anyone can set it to any value, including a negative number. By using methods, we can add rules and checks (like not allowing withdrawals beyond the available amount).

Example 2: Encapsulation in a Student Record

Now let’s create a Student class with encapsulated data like name and grade.

CLASS Student:
    PRIVATE name
    PRIVATE grade

    METHOD constructor(studentName, studentGrade):
        name = studentName
        IF studentGrade >= 0 AND studentGrade <= 100 THEN
            grade = studentGrade
        ELSE
            grade = 0

    METHOD setGrade(newGrade):
        IF newGrade >= 0 AND newGrade <= 100 THEN
            grade = newGrade

    METHOD getGrade():
        RETURN grade
Student grade is validated before being updated.

Explanation:

Here we encapsulated grade so that it is only changed through setGrade(). This ensures that no invalid grades can be set (like -10 or 120).

Another Question:

Q: Can we still read the values if they are private?

A: Yes, by providing public methods like getGrade() or getBalance(), we can safely expose values without making them publicly modifiable.

Key Takeaways:

  • Encapsulation protects data from unintended interference.
  • Use accessors (getters) and mutators (setters) to control how variables are accessed or changed.
  • Encapsulation makes programs more reliable and secure.

Try It Yourself

Create a Car class with encapsulated data for speed. Add methods to increase or decrease speed, ensuring it doesn’t go below 0 or above a defined max.

Q: What problems might arise if you make all data public?

A: Think through edge cases — wrong data formats, invalid ranges, conflicting values — and you’ll quickly see why encapsulation is a good practice.

Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗