Encapsulation and Abstraction


Encapsulation from what you have learnt googling around, is a concept of combining the related data and operations in a single capsule or what we could say a ‘class’ in OOP, such that no other program can modify the data it holds or method implementation it has, at a particular instance of time. Only the getter and setter methods can provide access to the instance variables.

It is always a good practice to provide access to instance variables through getter and setter methods. The calling code always going through methods instead of direct access to the instance variables adds to better maintainability, extensibility and design.

Our code might be used by others and future up-gradations or bug fixes are liable. Encapsulation is something that makes sure that whatever code changes we do in our code doesn’t break the code of others who are using it.

Encapsulation adds up to the maintainability, flexibility and extensibility of the code.

Encapsulation helps hide the implementation behind an interface.


Abstraction is the process of actually hiding the implementation behind an interface. So we are just aware of the actual behavior but not how exactly the think works out internally. The most common example could be the scenario where we put a key inside the lock and easily unlock it. So the interface here is the keyhole, while we are not aware of how the levers inside the lock co-ordinate among themselves to get the lock unlocked.

To be more clear, abstraction can be explained as the capability to use the same interface for different objects. Different implementations of the same interface can exist, while the details of every implementation are hidden or capsulated by encapsulation.

Abstraction in Java can be achieved by two ways:

  1. Using Abstract methods
  2. Using Interfaces

Finally, the statement to answer all the confusions until now –

The part that is hidden relates to encapsulation while the part that is exposed relates to abstraction.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.