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 *