What is the difference between abstraction and encapsulation?
Abstraction and encapsulation are core object-oriented programming concepts, but they serve different purposes:
- Abstraction:
-
Focuses on hiding complexity by showing only the essential details.
-
Achieved using abstract classes and interfaces.
-
Example: A car’s steering hides the internal mechanisms like the engine or gears.
-
- Encapsulation:
-
Focuses on hiding data by restricting direct access to it.
-
Achieved using private fields and providing access through getters/setters.
-
Example: A car’s speed is controlled by the accelerator, not directly accessed.
-
In short:
Abstraction: Hides implementation details.
Encapsulation: Hides data and enforces control.