About

Encapsulation and Abstraction

Encapsulation and Abstraction

Encapsulation and abstraction form two of the foundational pillars of object-oriented design. While closely related, they address distinct engineering concerns.

Encapsulation: Protect and Control

Encapsulation is the bundling of data and the methods that act on that data inside a boundary (typically a class), restricting direct access to internal components.

public class BankAccount {
    private double balance;

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

    public double getBalance() {
        return balance;
    }
}

Exam Rule: Encapsulation is not simply using private variables. It is about grouping related data and operations together and controlling access through a well-defined public interface.

Abstraction: Hide Complexity

Abstraction means exposing essential features while concealing implementation mechanisms. It enables developers to focus on what an object does rather than how it executes it.

For example, when driving a vehicle:

car.start();

The driver interacts with the ignition mechanism without needing to comprehend ignition timing, fuel injectors, or electrical solenoids.

Memory Comparison Rule

Exercise 1

Why does making fields private support the principle of encapsulation?

Show solution ↓
Solution

It restricts outside code from directly altering internal data without validation, preserving class invariants and reducing coupling between components.