[java] Encapsulation vs Abstraction?

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

This question is related to java oop

The answer is


Abstraction delineates a context-specific, simplified representation of something; it ignores contextually-irrelevant details and includes contextually-important details.

Encapsulation restricts outside access to something's parts and bundles that thing's state with the procedures that use the state.


Take people, for instance. In the context of surgery a useful abstraction ignores a person's religious beliefs and includes the person's body. Further, people encapsulate their memories with the thought processes that use those memories. An abstraction need not have encapsulation; for instance, a painting of a person neither hides its parts nor bundles procedures with its state. And, encapsulation need not have an associated abstraction; for instance, real people (not abstract ones) encapsulate their organs with their metabolism.


Encapsulation - the process of hiding components of the class to prevent direct access from the outside. It is achieved by using "private" modifier to prevent direct access to some class members (data field or method) from other classes or objects meanwhile providing access to these private members by public members (Interface). That make the class members protected as human organs hidden/encapsulated under the skin or some shield.

Abstraction - A principle must be followed in writing OOP program that say "you must include in the class only components that are interesting in the task of the program". For example: the object student has a lot of characters as a human: name, age, weight, hair color, eye color, etc. But, when you create a class in OOP to work with students you should include only those characters that really matter for student database: name, age, specialty, level, marks ... etc. in C++ you can create abstract class by using the modifier "virtual" with any methods in the class and that will make it unusable in direct but you can derive other classes from it and create implementation for its members with adding required members based on the task.


Encapsulation is hiding unnecessary data in a capsule or unit

Abstraction is showing essential feature of an object

Encapsulation is used to hide its member from outside class and interface.Using access modifiers provided in c#.like public,private,protected etc. example:

Class Learn
{
  private int a;         // by making it private we are hiding it from other
  private void show()   //class to access it
  {
   console.writeline(a);
  }
}

Here we have wrap data in a unit or capsule i.e Class.

Abstraction is just opposite of Encapsulation.

Abstraction is used to show important and relevant data to user. best real world example In a mobile phone, you see their different types of functionalities as camera, mp3 player, calling function, recording function, multimedia etc. It is abstraction, because you are seeing only relevant information instead of their internal engineering.

 abstract class MobilePhone
    {
        public void Calling();       //put necessary or essential data
        public void SendSMS();       //calling n sms are main in mobile
    }

    public class BlackBerry : MobilePhone   // inherited main feature
    {
        public void FMRadio();            //added new
        public void MP3();
        public void Camera();
        public void Recording();

    }

Lets try to understand in a different way.

What may happen if Abstraction is not there and What may happen if Encapsulation is not there.

If Abstraction is not there, then you can say the object is use less. You cannot identify the object nor can you access any functionality of it. Take a example of a TV, if you do not have an option to power on, change channel, increase or decrease volume etc., then what's the use of TV and how do you use it ?

If Encapsulation is not there or not being implemented properly, then you may misuse the object. There by data/components may get misused. Take the same example of TV, If there is no encapsulation done to the volume of TV, then the volume controller may be misused by making it come below or go beyond its limit (0-40/50).


NOTE: I am sharing this. It is not mean that here is not good answer but because I easily understood.

Answer:

When a class is conceptualized, what are the properties we can have in it given the context. If we are designing a class Animal in the context of a zoo, it is important that we have an attribute as animalType to describe domestic or wild. This attribute may not make sense when we design the class in a different context.

Similarly, what are the behaviors we are going to have in the class? Abstraction is also applied here. What is necessary to have here and what will be an overdose? Then we cut off some information from the class. This process is applying abstraction.

When we ask for difference between encapsulation and abstraction, I would say, encapsulation uses abstraction as a concept. So then, is it only encapsulation. No, abstraction is even a concept applied as part of inheritance and polymorphism.

Go here for more explanation about this topic.


encapsulation is a part of abstraction or we can say its a subset of abstraction

They are different concepts.

  • Abstraction is the process of refining away all the unneeded/unimportant attributes of an object and keep only the characteristics best suitable for your domain.

    E.g. for a person: you decide to keep first and last name and SSN. Age, height, weight etc are ignored as irrelevant.

    Abstraction is where your design starts.

  • Encapsulation is the next step where it recognizes operations suitable on the attributes you accepted to keep during the abstraction process. It is the association of the data with the operation that act upon them.
    I.e. data and methods are bundled together.

This is how I understood it:

In Object oriented programming, we have something called classes. What are they for? They are to store some state and to store some methods to change that state i.e., they are encapsulating state and its methods.

It(class) does not care about the visibility of its own or of its contents. If we choose to hide the state or some methods, it is information hiding.

Now, take the scenario of an inheritance. We have a base class and a couple of derived (inherited) classes. So, what is the base class doing here? It is abstracting out some things from the derived classes.

All of them are different, right? But, we mix them up to write good object oriented programs. Hope it helps :)


in a simple sentence, I cay say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change. You might consider abstraction is same as encapsulation. But encapsulation means the act of enclosing one or more items within a container, not hiding details. If you make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).


Abstraction is a very general term, and abstraction in software is not limited to object-oriented languages. A dictionary definition: "the act of considering something as a general quality or characteristic, apart from concrete realities, specific objects, or actual instances".

Assembly language can be thought of as an abstraction of machine code -- assembly expresses the essential details and structure of the machine code, but frees you from having to think about the opcodes used, the layout of the code in memory, making jumps go to the right address, etc.

Your operating system's API is an abstraction of the underlying machine. Your compiler provides a layer of abstraction which shields you from the details of assembly language. The TCP/IP stack built into your operating system abstracts away the details of transmitting bits over a network. If you go down all the way to the raw silicon, the people who designed your CPU did so using circuit diagrams written in terms of "diodes" and "transistors", which are abstractions of how electrons travel through semiconductor crystals.

In software, everything is an abstraction. We build programs which simulate or model some aspect of reality, but by necessity our models always abstract away some details of the "real thing". We build layer on layer on layer of abstractions, because it is the only way we get anything done. (Imagine you were trying to make, say, a sudoku solver, and you had to design it using only semiconductor crystals. "OK, I need a piece of N-type silicon here...")

In comparison, "encapsulation" is a very specific and limited term. Some of the other answers to this question have already given good definitions for it.


Encapsulation protects to collapse the internal behaviour of object/instance from external entity. So, a control should be provided to confirm that the data which is being supplied is not going to harm the internal system of instance/object to survive its existance.

Good example, Divider is a class which has two instance variable dividend and divisor and a method getDividedValue.

Can you please think, if the divisor is set to 0 then internal system/behaviour (getDivided ) will break.

So, the object internal behaviour could be protected by throwing exception through a method.


Answering my own question after 5 years as i feel it still need more details

Abstraction:

Technical Definition :- Abstraction is a concept to hide unnecessary details(complex or simple) and only show the essential features of the object. There is no implementaion here its just an concept

What it means practically:- When i say my company needs some medium/device so that employees can connect to customer . This is the purest form of abstaction(like interface in java) as that device/medium can be phone or internet or skype or in person or email etc. I am not going into nitty gritty of device/medium

Even when i say my company needs some medium/device so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as device/medium can be phone or skype or something else etc

Now when i say my company needs some phone so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as phone can be of any company like iphone or samsung or nokia etc

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

What it means practically:- Now when i say my company needs some iphone so that employees can connect to customer through voice call.Now i am talking about some concrete object(like iphone). Even though i am not going into nitty gritty of iphone here too but iphone has some state/concrecrete info/implementation associated with it where device/medium does not have. When i say concrete object, actually it means any object which has some(not complete like java abstract class) implementation/info associated with it.

So iphone actually used here encapsulation as strategy to hide its state/information and expose only the ones which it think should be exposed. So both abstraction and encapsulation hides some unnecessary details but abstraction at the concept level and encapsulation actually at implementation level

This 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

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.