Abstraction vs Encapsulation

 In Java, abstraction and encapsulation are both core Object-Oriented Programming (OOP) concepts, but they serve different purposes.



Abstraction

What it means:

Abstraction is hiding implementation details and showing only essential features.

It focuses on what an object does, not how it does it.


How it’s achieved in Java:

  • abstract classes

  • interfaces


Java Example (Abstraction using interface)

interface Payment {
    void pay(double amount);  // only method declaration (what to do)
}

class CreditCardPayment implements Payment {
    @Override
    public void pay(double amount) {
        System.out.println("Processing credit card payment of $" + amount);
    }
}

public class Main {
    public static void main(String[] args) {
        Payment payment = new CreditCardPayment();
        payment.pay(100);
    }
}


Explanation:

  • The Payment interface defines what should be done (pay()).

  • The implementation details (how payment is processed) are hidden inside CreditCardPayment.

  • The user of Payment doesn’t need to know how it works internally.



Encapsulation

What it means:

Encapsulation is wrapping data (variables) and methods together and restricting direct access to some of the object’s components.

It focuses on data protection.


How it’s achieved in Java:

  • private variables

  • Public getters and setters


Java Example (Encapsulation)

class BankAccount {
    private double balance;  // hidden data

    public double getBalance() {
        return balance;
    }

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

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.deposit(500);
        System.out.println(account.getBalance());
    }
}


Explanation:

  • balance is private → cannot be accessed directly.

  • Access is controlled through deposit() and getBalance().

  • This protects the object’s internal state.



 Key Differences

AbstractionEncapsulation
Hides implementation detailsHides internal data
Focuses on behavior (what)Focuses on data protection
Achieved using interfaces & abstract classesAchieved using access modifiers
Design-level conceptImplementation-level concept


Simple Analogy

  • Abstraction → Driving a car: You use the steering wheel and pedals without knowing how the engine works.

  • Encapsulation → The car’s engine is hidden under the hood so you can’t directly modify its parts.


Nenhum comentário:

Postar um comentário

Abstraction vs Encapsulation

  In Java,   abstraction   and   encapsulation   are both core Object-Oriented Programming (OOP) concepts, but they serve different purposes...