Difference Between Abstraction and Encapsulation in C#
Difference Between Abstraction and Encapsulation in C#
Both Abstraction and Encapsulation are fundamental concepts of Object-Oriented Programming (OOP), but they serve different purposes. Let’s break them down clearly with code examples and key comparisons.
๐ What is Abstraction?
Abstraction is the process of hiding implementation details and exposing only the essential features of an object. It focuses on what an object does rather than how it does it.
✅ How Abstraction is Implemented:
๐งช Example:
public interface IPrinter
{
void Print();
}
public class LaserPrinter : IPrinter
{
public void Print()
{
// Complex logic hidden from user
Console.WriteLine("Printing document...");
}
}
Here, the user interacts with the IPrinter interface without knowing the internal logic of LaserPrinter.
๐ What is Encapsulation?
Encapsulation is the technique of wrapping data (fields) and code (methods) into a single unit and restricting direct access to some of the object's components.
✅ How Encapsulation is Achieved:
- Using
privatefields - Exposing controlled access via
publicmethods
๐งช Example:
public class BankAccount
{
private decimal balance;
public void Deposit(decimal amount)
{
if (amount > 0)
balance += amount;
}
public decimal GetBalance()
{
return balance;
}
}
The internal field balance cannot be accessed directly, providing better data protection.
๐ Key Differences: Abstraction vs Encapsulation
| Feature | Abstraction | Encapsulation |
|---|---|---|
| Definition | Hides implementation details; shows only relevant features | Hides data and internal state using access control |
| Purpose | Reduce complexity | Protect data integrity |
| Focus | What the object does | How data is accessed or modified |
| Achieved Using | Interfaces, abstract classes | Private fields, public methods |
| Real-World Analogy | TV remote (user knows what buttons do, not how they work) | ATM (securely encapsulates cash and logic inside) |
๐ง Summary
Abstraction is about design — exposing the necessary behavior while hiding implementation logic.
Encapsulation is about security and control — hiding data and ensuring proper access through defined methods.
✅ When to Use What?
- Use abstraction when designing reusable contracts and APIs.
- Use encapsulation when you need to secure object state and enforce business rules.
In modern C# applications, both are used together to create clean, secure, and maintainable code structures.

Comments
Post a Comment