Both abstraction and encapsulation are OOPS concepts and that is one of the similarity between these two terms, other being that you will hear the term “hiding” when both encapsulation and abstraction are talked about but that is where the similarities end. Both of these concepts have their own specific purpose which is quite different from one another and that’s what is the topic of this post Difference between Encapsulation and Abstraction in Java.
Encapsulation Vs Abstraction in Java
- Encapsulation is about keeping together the data and the methods that act on that data. Focus is more on safety of data that is why encapsulation is a data hiding mechanism.
Abstraction means hiding the implementation details and exposing only the essential features to the user. Focus here is more on hiding the complexity and giving just enough information to the user to know how to use the functionality without knowing how it is actually implemented.
- A Java class is the building block of encapsulation in Java by keeping data and the methods wrapped with in a class. Encapsulation is achieved by using the access modifiers – public, private, protected and default (package-private). By restricting the access using the proper modifier any accidental or intentional misuse by the outside entity is avoided.
Abstraction in Java is implemented through interfaces and abstract classes. Interfaces and abstract classes have abstract methods which just tell the user about the method that can be accessed but how it is implemented is hidden.
Different classes implementing the interface or extending the abstract class can provide different implementation of the abstract methods but user can access any of the implementation by invoking the same method.
- Encapsulation helps in managing the code by keeping what changes at one place which makes code easy to maintain. Encapsulation promotes the design principle “Encapsulate what varies”.
Abstraction provides a contract for the class, how the class methods will be accessed without actually providing what methods should do. Abstraction promotes the design principle “Program to interfaces, not implementations”.
- Abstraction puts more focus on what the code is doing, not how it does it.
Encapsulation puts more focus on how an object does something but hides the internal details of an object by restricting access.
That’s all for the topic Difference Between Encapsulation And Abstraction in Java – OOPS Concepts. If something is missing or you have something to share about the topic please write a comment.
You may also like
- Method Overloading in Java
- Overview of Exception Handling in Java
- LinkedList Internal Implementation in Java
- ConcurrentHashMap in Java
- How to Convert int to String in Java
- Frequently Used HDFS Commands