Difference Between Abstraction and Encapsulation in C#
Difference
Between Abstraction and Encapsulation in C#
Both Abstraction and Encapsulation
are fundamental principles of Object-Oriented Programming (OOP). They may sound
similar, but they address different concerns:
What is Abstraction?
- Abstraction
is the process of hiding the implementation details and showing
only the essential features of an object.
- It
focuses on what an object does, rather than how it does it.
- Implemented
using:
- Interfaces
- Abstract classes
Example:
public interface
IPrinter
{
void Print();
}
public class
LaserPrinter : IPrinter
{
public void Print()
{
// complex logic hidden
Console.WriteLine("Printing
document...");
}
}
In this example, the interface abstracts the
printing operation. The user only knows about Print() but not the internal
steps.
What is Encapsulation?
- Encapsulation
is the process of binding data (fields) and methods that manipulate
the data into a single unit (class), and restricting direct access
to some of the object's components.
- It
protects the object’s integrity by preventing unintended interference.
- Achieved
using access modifiers like private, protected, public.
Example:
public class
BankAccount
{
private decimal balance;
public void Deposit(decimal amount)
{
if (amount > 0)
balance += amount;
}
public decimal GetBalance()
{
return balance;
}
}
Here, the internal balance is encapsulated. It
can’t be directly accessed or modified from outside the class.
Key Differences
Between Abstraction and Encapsulation
Feature |
Abstraction |
Encapsulation |
Purpose |
Hides complexity; shows only relevant data |
Hides data; restricts direct access |
Focus |
On what the object does |
On how data is protected and accessed |
Implementation |
Interfaces, abstract classes |
Classes with private fields and public
methods |
Used For |
Designing clean APIs and contracts |
Securing internal object state |
Visibility |
Hides implementation details |
Hides data/internal state |
Summary
- Abstraction
is about design: exposing necessary functionality while hiding
internal logic.
- Encapsulation
is about security and control: bundling data and controlling
access.
In practice, both are used together:
- Abstraction
helps reduce complexity.
- Encapsulation
helps protect and organize the internal state.
Comments
Post a Comment