OOP: ABSTRACTION
Abstraction vs Encapsulation
Abstraction and encapsulation are related, but they are not the same.
Short Difference
Abstraction -> hides unnecessary implementation details.
Encapsulation -> protects internal data by controlling access.
Comparison Table
| Topic | Abstraction | Encapsulation |
|---|---|---|
| Main question | What should the user see? | How should data be protected? |
| Focus | Interface and essential behavior | Data hiding and validation |
| Hides | Implementation complexity | Internal state |
| Achieved by | Public methods, abstract classes, pure virtual functions | Classes, private data, getters/setters, controlled methods |
| Example | payment->process() |
balance is private and changed through deposit() |
Example of Encapsulation
class BankAccount {
private:
double balance;
public:
void deposit(double amount);
bool withdraw(double amount);
};
Here, balance is protected from direct access.
Example of Abstraction
class PaymentProcessor {
public:
virtual ~PaymentProcessor() = default;
virtual void process(double amount) const = 0;
};
Here, the user only knows the interface process(). The internal payment details are hidden in derived classes.
How They Work Together
Encapsulation often helps build abstraction.
For example, a BankAccount hides its balance using encapsulation. Then it exposes meaningful operations like:
deposit(amount);
withdraw(amount);
Those public methods form an abstraction for using the account.
Viva Answer
Abstraction hides unnecessary implementation details and shows only the essential interface. Encapsulation hides and protects internal data by controlling access. Encapsulation can help implement abstraction, but they are not the same concept.
Quick Check
- Which concept hides implementation complexity?
- Which concept protects internal state?
- Can encapsulation help create abstraction?