Data Abstraction and Encapsulation
1. What is Data Abstraction?
Data Abstraction is the process of hiding internal implementation details and showing only the essential features of an object.
🎯 Purpose:
-
To reduce complexity.
-
To focus only on what an object does rather than how it does it.
✅ Example of Data Abstraction:
💡 Explanation:
-
Animal
is an abstract class. -
makeSound()
is an abstract method: only its signature is visible. -
The actual implementation is hidden in the subclass (
Dog
). -
The user (main program) only cares about the method being called, not its internal logic.
🔐 Ways to Achieve Abstraction in Java:
Technique | Description |
---|---|
Abstract Class | Contains abstract methods that subclasses must implement. |
Interfaces | Define what a class must do but not how. (All methods are implicitly abstract unless using default/static.) |
2. What is Encapsulation?
Encapsulation is the concept of binding data and methods that operate on that data into a single unit (class) and restricting direct access to some of the object's components.
🎯 Purpose:
-
To protect data from unauthorized access.
-
To allow controlled access through getters and setters.
✅ Example of Encapsulation:
💡 Explanation:
-
The field
balance
is private. -
Access is only allowed via public methods like
getBalance()
anddeposit()
. -
This is encapsulation — data is protected from external modification.
🔍 Comparison Between Abstraction and Encapsulation
Feature | Data Abstraction | Encapsulation |
---|---|---|
Focus | What an object does | How data is hidden and accessed |
Hides | Implementation details | Internal data using access modifiers |
Achieved by | Abstract classes and interfaces | Classes, access modifiers, getters/setters |
Goal | Reduce complexity | Protect data and ensure safety |
Real-world Analogy
Concept | Real-life Example |
---|---|
Abstraction | Using a TV remote – you press buttons (what it does), but don’t know how circuits inside work. |
Encapsulation | A capsule (medicine) – the ingredients (data) are hidden inside, but you consume it as a whole. |
✅ Summary
-
Abstraction = Hiding internal implementation and showing only essential behavior.
-
Encapsulation = Hiding internal data and providing controlled access through methods.
Comments
Post a Comment