Java – Encapsulation vs Abstraction

javaoop

Here are the brief definitions of encapsulation and abstraction.

Abstraction:

The process of abstraction in Java is used to hide certain details and
only show the essential features of the object. In other words,
it deals with the outside view of an object (interface). The only good example i see for this across different sites is
interface.

Encapsulation:

Its basically about hiding the state of object with the help of
modifiers like private,public,protected etc. we expose the state thru
public methods only if require.

What we achieve with modifiers like private, public also hides unnecessary details from out side world which is nothing but also a abstraction concept

So, from above explanation looks like encapsulation is a part of abstraction or we can say it's a subset of abstraction. But why then encapsulation term is invented when we could deal it with abstraction only? I am sure there should be some major difference which distinguishes them but most of material on net says almost same thing for both of them.

Though this question has been raised on this forum earlier too but I am posting it again with specific doubts. Some replies also says abstraction is a concept and encapsulation is implementation. But I don't buy this – If it is true, then I can think these two different concepts are provided to confuse us.

Update:- After 5 years i have come up with my own answer whichs is the gist based on answers in this post and below ones

  1. difference between abstraction and encapsulation?
  2. encapsulation vs abstraction real world example

Best Answer

Abstraction is the concept of describing something in simpler terms, i.e abstracting away the details, in order to focus on what is important (This is also seen in abstract art, for example, where the artist focuses on the building blocks of images, such as colour or shapes). The same idea translates to OOP by using an inheritance hierarchy, where more abstract concepts are at the top and more concrete ideas, at the bottom, build upon their abstractions. At its most abstract level there is no implementation details at all and perhaps very few commonalities, which are added as the abstraction decreases.

As an example, at the top might be an interface with a single method, then the next level, provides several abstract classes, which may or may not fill in some of the details about the top level, but branches by adding their own abstract methods, then for each of these abstract classes are concrete classes providing implementations of all the remaining methods.

Encapsulation is a technique. It may or may not be for aiding in abstraction, but it is certainly about information hiding and/or organisation. It demands data and functions be grouped in some way - of course good OOP practice demands that they should be grouped by abstraction. However, there are other uses which just aid in maintainability etc.