July 7, 2022

Encapsulation Vs Abstraction in Java - OOPS Concepts

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

  1. 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.
  2. 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.
  3. 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”.
  4. 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 Encapsulation Vs 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

No comments:

Post a Comment