Difference between Encapsulation and Abstraction

Question:

I had an interview today. I had a question from OOP, about the difference between Encapsulation & Abstraction?

I replied to my knowledge that Encapsulation is basically binding data members & member functions into a single unit called Class. Whereas Abstraction is basically to hide implementation complexity & provide ease of access to the users. I thought she would be okay with my answer. But she queried if the purpose of both is to hide information then what the actual difference between these two is? I could not give any answer to her.

Before asking this question, I read other threads on StackOverFlow about the difference between these two OOPs concepts. But I am not finding myself in a position to convince the interviewer.

Can anyone please justify it with the simplest example?

Asked By: WpfBee

||

Answers:

Abstraction:
Is usually done to provide polymorphic access to a set of classes.
An abstract class cannot be instantiated thus another class will have to derive from it to create a more concrete representation.

A common usage example of an abstract class can be an implementation of a template method design pattern where an abstract injection point is introduces so that the concrete class can implement it in its own “concrete” way.

see: http://en.wikipedia.org/wiki/Abstraction_(computer_science)

Encapsulation:
It is the process of hiding the implementation complexity of a specific class from the client that is going to use it, keep in mind that the “client” may be a program or event the person who wrote the class.

see: http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)

Answered By: Mortalus

Encapsulation hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.

Abstraction is used to hide something too, but in a higher degree (class, interface). Clients who use an abstract class (or interface) do not care about what it was, they just need to know what it can do.

Answered By: phnkha

Abstraction – is the process (and result of this process) of identifying the common essential characteristics for a set of objects.
One might say that Abstraction is the process of generalization: all objects under consideration are included in a superset of objects, all of which possess given properties (but are different in other respects).

Encapsulation – is the process of enclosing data and functions manipulating this data into a single unit, so that to hide the internal implementation from the outside world.

This is a general answer not related to a specific programming language (as was the question). So the answer is: abstraction and encapsulation have nothing in common. But their implementations might relate to each other (say, in Java: Encapsulation – details are hidden in a class, Abstraction – details are not present at all in a class or interface).

Answered By: TT_

difference in both is just the View Point
Encapsulation word is used for hiding data if our aim is to prevent client seeing inside view of our logic

Abstraction word is used for hiding data if our aim is to show our client a out side view

Outside view means that let suppose

BubbleSort(){
//code 
swap(x,y);
}

here we use swap in bubble sort for just showing our client what logic we are applying, If we replace swap(x,y) with whole code here, In a single instance he/she can’t understand our logic

Answered By: Iqbal Haider

Abstraction: what are the minimum functions and variables that should be exposed to the outside of our class.

Encapsulation: how to achieve this requirement, meaning how to implement it.

There is a great article that touches on differences between Abstraction, Encapsulation and Information hiding in depth: http://www.tonymarston.co.uk/php-mysql/abstraction.txt

Here is the conclusion from the article:

Abstraction, information hiding, and encapsulation are very different,
but highly-related, concepts. One could argue that abstraction is a
technique that helps us identify which specific information should be
visible, and which information should be hidden. Encapsulation is then
the technique for packaging the information in such a way as to hide
what should be hidden, and make visible what is intended to be
visible.

Answered By: Manish Kumar Sharma

Abstraction

In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.

Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.

Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.

Encapsulation:

Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.

  1. If I have individual package one for wine and another one for chocolate, and if all the classes are declared in the package as default access modifier, we are giving package level encapsulation for all classes.
  2. Within a package, if we declare each class filed (member field) as
    private and having a public method to access those fields, this way
    giving class level encapsulation to those fields
Answered By: Shaan

Encapsulation:

Hiding something, sort of like medicine capsule. We don’t know what is in the capsule, we just take it. Same as in programming – we just hide some special code of method or property and it only gives output, same as capsule. In short, encapsulation hides data.

Abstraction:

Abstraction means hiding logic or implementation. For example, we take tablets and see their color and but don’t know what is the purpose of this and how it works with the body.

Answered By: Zeeshan Haider

This image sums pretty well the difference between both:

enter image description here

Source here

Answered By: José Salgado

Yes, it is true that Abstraction and Encapsulation are about hiding.

  • Using only relevant details and hiding unnecessary data at Design Level is called Abstraction. (Like selecting only relevant properties for a class ‘Car’ to make it more abstract or general.)

  • Encapsulation is the hiding of data at Implementation Level. Like how to actually hide data from direct/external access. This is done by binding data and methods to a single entity/unit to prevent external access. Thus, encapsulation is also known as data hiding at implementation level.

Answered By: CodeFu

Encapsulation: Wrapping code and data together into a single unit. Class is an example of encapsulation, because it wraps the method and property.

Abstraction: Hiding internal details and showing functionality only. Abstraction focus on what the object does instead of how it does. It provides generalized view of classes.

int number = 5;
string aStringNumber = number.ToString(); 

Here, ToString() is abstraction. And how this mechanism number variable converted to string and initialize into aStringNumber is encapsulation.

Let us take a real world example of calculator. Encapsulation is the internal circuits, battery, etc., that combine to make it a calculator. Abstraction is the different buttons like on-off, clear and other buttons provided to operate it.

Answered By: Arif

Just a few more points to make thing clear,

One must not confuse data abstraction and the abstract class. They are different.

Generally we say abstract class or method is to basically hide something. But no.. That is wrong. What is the word abstract means ? Google search says the English word abstraction means

“Existing in thought or as an idea but not having a physical or concrete existence.”

And thats right in case of abstract class too. It is not hiding the content of the method but the method’s content is already empty (not having a physical or concrete existence) but it determines how a method should be (existing in thought or as an idea) or a method should be in the calss.

So when do you actually use abstract methods ?

  • When a method from base class will differ in each child class that extends it.
  • And so you want to make sure the child class have this function implemented.
  • This also ensures that method, to have compulsory signature like, it must have n number of parameters.

So about abstract class!
– An Abstract class cannot be instantiated only extended! But why ?

  • A class with abstract method must be prevented from creating its own instance because the abstract methods in it, are not having any meaningful implementation.
  • You can even make a class abstract, if for some reason you find that it is meaning less to have a instance of your that class.

An Abstract class help us avoid creating new instance of it!

An abstract method in a class forces the child class to implement that function for sure with the provided signature!

Answered By: S Vinesh

Let me explain it in with the same example discussed above. Kindly consider the same TV.

Encapsulation: The adjustments we can make with the remote is a good example – Volume UP/DOWN, Color & Contrast – All we can do is adjust it to the min and max value provided and cannot do anything beyond what is provided in the remote – Imagine the getter and setter here(The setter function will check whether the value provided is valid if Yes, it process the operation if not won’t allow us to make changes – like we cannot decrease the volume beyond zero even we press the volume down button a hundred times).

Abstraction: We can take the same example here but with a higher Degree/Context. The volume down button will decrease the volume – and this is the info we provide to the user and the user is not aware of neither the infrared transmitter inside the remote nor the receiver in the TV and the subsequent process of parsing the signal and the microprocessor architecture inside the TV. Simply put it is not needed in the context – Just provide what is necessary. One can easily relate the Text book definition here ie., Hiding the inner implementation and only providing what it will do rather than how it do that!

Hope it clarifies a bit!

Answered By: Surya

If I am the one who faced the interview, I would say that as the end-user perspective abstraction and encapsulation are fairly same. It is nothing but information hiding. As a Software Developer perspective, Abstraction solves the problems at the design level and Encapsulation solves the problem in implementation level

Answered By: Rasika Weragoda

Briefly, Abstraction happens at class level by hiding implementation and implementing an interface to be able to interact with the instance of the class. Whereas, Encapsulation is used to hide information; for instance, making the member variables private to ban the direct access and providing getters and setters for them for indicrect access.

Answered By: Morteza Bandi

Yes !!!!
If I say Encapsulation is a kind of an advanced specific scope abstraction,

How many of you read/upvote my answer. Let’s dig into why I am saying this.

I need to clear two things before my claim.

One is data hiding and, another one is the abstraction

Data hiding

Most of the time, we will not give direct access to our internal data. Our internal data should not go out directly that is an outside person can’t access our internal data directly. It’s all about security since we need to protect the internal states of a particular object.

Abstraction

For simplicity, hide the internal implementations is called abstraction. In abstraction, we only focus on the necessary things. Basically, We talk about “What to do” and not “How to do” in abstraction.
Security also can be achieved by abstraction since we are not going to highlight “how we are implementing”. Maintainability will be increased since we can alter the implementation but it will not affect our end user.

I said, "Encapsulation is a kind of an advanced specific scope abstraction". Why? because we can see encapsulation as data hiding + abstraction

encapsulation = data hiding + abstraction

In encapsulation, we need to hide the data so the outside person can not see the data and we need to provide methods that can be used to access the data. These methods may have validations or other features inside those things also hidden to an outside person. So here, we are hiding the implementation of access methods and it is called abstraction.

This is why I said like above encapsulation is a kind of abstraction.

So Where is the difference?

The difference is the abstraction is a general one if we are hiding something from the user for simplicity, maintainability and security and,

encapsulation is a specific one for which is related to internal states security where we are hiding the internal state (data hiding) and we are providing methods to access the data and those methods implementation also hidden from the outside person(abstraction).

Why we need abstraction
When you do designs, you will not talk about implementations. You say If you give these parameters to this method it will give these output.
We hide the internal implementation of the method and talk about what it will do so this is an abstraction.

Example

public int add(int a, int b);

This method definition tells us that if you give two variables it will do addition and return the result.

here we will not look at the implementation and we ay only what this method does and not how it does.
Method implementations can be differs based on developers.
1.

public int add(int a, int b){
   return a + b; 
}
public int add(int a, int b){

   return b + a; 
}

Two methods are doing the same thing what their implementation differs.

Basically,

Abstraction is needed to model the system. Encapsulation is needed to enhance system security.

Answered By: RCvaram

A very practical example is.

let’s just say I want to encrypt my password.

  • I don’t want to know the details, I just call
    encryptionImpl.encrypt(password) and it returns an encrypted
    password.

    public interface Encryption{ public String encrypt(String password); }

    This is called abstraction. It just shows what should be done.

  • Now let us assume We have Two types of Encryption Md5 and RSA which
    implement Encryption from a third-party encryption jar.

    Then those Encryption classes have their own way of implementing
    encryption which protects their implementation from outsiders

    This is called Encapsulation. Hides how it should be done.

Remember:what should be done vs how it should be done.

Hiding complications vs Protecting implementations

Answered By: Monu chandramohan

Encapsulation is wrapping up of data and methods in a single unit and making the data accessible only through methods(getter/setter) to ensure safety of data.

Abstraction is hiding internal implementation details of how work is done.

Take and example of following stack class:

Class Stack
{
private top;
void push();
int pop();
}

Now encapsulation helps to safeguard internal data as top cannot be accessed directly outside.

And abstraction helps to do push or pop on stack without worrying about what are steps to push or pop

Answered By: rahul sharma

Abstraction
As the name suggests abstract means summary or brief about somtehing. In case of OOP Abstract Classes are the ones which do not contain every information about that object in real world, for eg. you want to book a hotel room, if your object is that room you mainly care about:

  • its prices, size, beds etc.

but you do not care about

  • the wiring they have used in the hotel room for electricity.
  • which cement they have used to build it up

So, you get abstracted information about the room which you care about.

On the other hand, Encapsulation is basically capsulating the related information together, for eg. you booked the hotel room, you go there and switch on a bulb by pressing the switch. Now the switch object has all internal wirings which are required to switch that bulb ON, but you really do not care about those wirings. You care only about bulb is switched ON or not.

Now one can argue that abstraction also applies here:

one can say the internal wiring of the switch is also abstracted to you, so this must be case of abstraction but here are some subtle differences:

Abstraction is more of a contextual thing, it does not have the non abstracted information, like the wiring info which you do not care about, is not present in the context of website for booking hotel room (like your class room do not have information about the wiring grid of it, since this room is delegated for online booking only) , whereas encapsulation is more granular, it means hiding and capsulating the granular things which you do not need to care about, for switching the bulb ON the switch hides the wiring inside the switch board (like private attributes/methods of classes).
Now the switch class has the information but it is hidden to you. On the other hand room class does not have the information about wiring design of a hotel room since it is not even in the context of online booking of the room

Thus, the abstraction is more related to classes and encapsulation is more related to internal of the class objects, attributes and methods.

Answered By: Shubham Rajput

Abstraction

  • is the process of hiding the how, and only showing the what
  • the purpose is to simplify information and hide unnecessary details from the user

Encapsulation

  • is the process of wrapping data and functionality into a single unit
  • the purpose is to protect data, by preventing direct access and only providing a safer and indirect way
Answered By: Grateful

In simple terms, Encapsulation is data hiding(information hiding) while Abstraction is detail hiding(implementation hiding)

Answered By: Reyan Chougle

Encapsulation is the composition of meaning.

Abstraction is the simplification of meaning.

Answered By: sacretruth