![]() |
VOOZH | about |
Abstraction and Encapsulation are two fundamental concepts of Object-Oriented Programming in Java. Both help in designing secure, maintainable, and flexible applications, but they serve different purposes. Understanding their difference is important for writing clean and scalable code.
Abstraction focuses on hiding implementation details and showing only the essential features of an object. It allows you to define what an object does without explaining how it does it.
Real-Life Example: When you drive a car, you just use the steering, brake, and accelerator. You don’t need to know how the engine works internally.
Car starts with key
Explanation: The Vehicle class declares an abstract method start() without implementation and Car class provides the actual implementation of the start() method. User only calls start() without knowing how it works internally (implementation is hidden).
Encapsulation focuses on wrapping data (variables) and methods into a single unit and restricting direct access to the data. It protects the internal state of an object.
Real-Life Example: A bank account does not allow direct access to balance. You can only access or modify it through methods like deposit() or withdraw().
90
Explanation: The variable marks is declared as private, so it cannot be accessed directly. The getMarks() method is used to read the value, and setMarks() is used to update it. This ensures controlled access and prevents invalid data from being assigned.
| Feature | Abstraction | Encapsulation |
|---|---|---|
| Definition | Abstraction is the process of hiding implementation details and showing only functionality to the user. | Encapsulation is the process of binding data and methods together and restricting direct access to data. |
| Focus | Abstraction focuses on what an object does rather than how it does it. | Encapsulation focuses on protecting data by controlling how it is accessed. |
| Goal | Abstraction helps reduce complexity and improve code maintainability. | Encapsulation helps ensure data security and maintain data integrity. |
| Level | Abstraction works at the design or interface level. | Encapsulation works at the implementation level. |
| Implementation | Abstraction is implemented using abstract classes and interfaces. | Encapsulation is implemented using access modifiers like private, public, and protected. |
| Data Handling | Abstraction exposes only the necessary features to the user. | Encapsulation hides data and provides controlled access using getters and setters. |