Saturday, 15 November 2025

Difference Between Encapsulation and Abstraction?

Encapsulation vs Abstraction

Encapsulation

  • Encapsulation is about hiding data and protecting it from outside access.
  • It bundles data and methods into a single unit (e.g., a class).
  • Achieved using access modifiers like private, protected, etc.
  • Controls how data is accessed or modified.
class Person {
    private int age; // hidden data

    public void SetAge(int value) { // controlled access
        if (value >= 0) age = value;
    }
}
    

Abstraction

  • Abstraction is about hiding complexity and showing only essential features.
  • Lets you focus on what something does rather than how it works.
  • Achieved using abstract classes and interfaces.
abstract class Animal {
    public abstract void MakeSound(); // only essential behavior shown
}
    

Summary

Encapsulation Abstraction
Hides internal data Hides implementation complexity
Protects the data Simplifies the design

Encapsulation = hiding data
Abstraction = hiding complexity

No comments:

Post a Comment