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?

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

Output:

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

Explanation:

In the above example:

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

Output:

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:

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.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M