what is difference between abstraction and encapsulation in java
Abstraction and encapsulation are two fundamental principles of object-oriented programming, and while they are closely related, they serve different purposes.
Let’s discuss each concept and highlight the key differences with examples.
Abstraction is the process of simplifying complex systems by modeling classes based on the essential properties and behaviors they exhibit. It involves creating abstract classes and interfaces that define the structure and behavior of a system without specifying the implementation details. Abstraction allows developers to focus on what an object does rather than how it achieves its functionality.
Example of Abstraction:
In this example,
Shape is an abstract class that defines the concept of a shape and declares an abstract method
Circle class is a concrete class that extends
Shape and provides an implementation for the
calculateArea method. The abstraction allows us to represent the common properties and behavior of various shapes without specifying the details of each shape’s implementation.
Encapsulation is the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, known as a class. It involves hiding the internal details of how an object achieves its functionality and exposing only what is necessary for the outside world to interact with the object. Encapsulation is achieved by declaring the data members of a class as private and providing public methods (getters and setters) for controlled access.
Example of Encapsulation:
In this example,
BankAccount encapsulates the concept of a bank account. The
balance is a private data member, and access to it is controlled through public methods (
setBalance). The encapsulation ensures that the internal details of the bank account, such as how the balance is stored or updated, are hidden from external users. It provides controlled access to the balance and allows validation before modifying the data.
- Abstraction: Focuses on modeling concepts and defining their essential properties and behaviors.
- Encapsulation: Focuses on bundling data and methods into a single unit and controlling access to the internal details.
2. Implementation vs. Interface:
- Abstraction: Deals with the abstraction of the interface, hiding implementation details.
- Encapsulation: Deals with bundling the implementation details and controlling access through an interface.
- Abstraction: Involves abstract classes and interfaces defining the structure and behavior without specifying implementation details.
- Encapsulation: Involves classes bundling data and methods, controlling access to the data through getters and setters.
In summary, abstraction is about modeling concepts at a high level, while encapsulation is about bundling data and methods and controlling access to them. Both principles work together to create modular, maintainable, and scalable object-oriented systems.