Difference Encapsulation and Abstraction ?

🔐 Encapsulation — “Protect the Data”

What It Is:

Encapsulation means wrapping data (variables) and methods (functions) together into a single unit, typically a class, and restricting direct access to some components using access modifiers (private, public, etc.).

🎯 Purpose:

  • To hide internal object details from outside interference.
  • To ensure control over data using getter and setter methods.

Example:

class BankAccount {
    private double balance; // Hidden from outside

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

    public void withdraw(double amount) {
        if(amount > 0 && amount <= balance) balance -= amount;
    }

    public double getBalance() {
        return balance;
    }
}

Here, you can’t access balance directly, only via controlled methods.


🎭 Abstraction — “Show Only What’s Necessary”

➤ What It Is:

Abstraction means hiding implementation details and only exposing essential features of an object.

You can achieve abstraction in Java using:

  • Abstract classes
  • Interfaces

🎯 Purpose:

  • To focus on what an object does, not how it does it.
  • Makes code more modular, extensible, and easier to understand.

✅ Example using Interface:

interface Vehicle {
    void start();   // Abstract method
    void stop();
}

class Car implements Vehicle {
    public void start() {
        System.out.println("Car starts with key");
    }
    public void stop() {
        System.out.println("Car stops with brake");
    }
}

The user of the Vehicle interface doesn’t care how the Car starts or stops—just that it does.

🧠 Side-by-Side Comparison

FeatureEncapsulationAbstraction
GoalHide dataHide complexity
FocusHow you protect dataHow you hide implementation logic
Accessed viaGetters and SettersAbstract classes and Interfaces
Achieved Usingprivate + public methodsabstract keyword / interfaces
HidesObject’s internal stateImplementation complexity
Used ForData hidingDesign flexibility
ExampleBanking system with account balanceInterface for all types of vehicles

Leave a Reply

Your email address will not be published. Required fields are marked *