[oop] Difference between Encapsulation and Abstraction

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

I replied her to my knowledge that Encapsulation is basically to bind data members & member functions into a single unit called Class. Whereas Abstraction is basically to hide complexity of implementation & provide ease of access to the users. I thought she would be fine with my answer. But she queried, if the purpose of both are to hide information then what is the actual difference between these two? 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 my self in a position to convince the interviewer.

Can anyone please justify it with a simplest example?

This question is related to oop encapsulation abstraction

The answer is


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!


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!


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


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)


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).


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


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.


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.


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


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.


This image sums pretty well the difference between both:

enter image description here

Source here


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.


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

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.


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 in why I am saying like this.

I need to clear two things before my claiming.

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 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).


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


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.


Examples related to oop

How to implement a simple scenario the OO way When to use 'raise NotImplementedError'? PHP: cannot declare class because the name is already in use Python class input argument Call an overridden method from super class in typescript Typescript: How to extend two classes? What's the difference between abstraction and encapsulation? An object reference is required to access a non-static member Java Multiple Inheritance Why not inherit from List<T>?

Examples related to encapsulation

What's the difference between abstraction and encapsulation? How abstraction and encapsulation differ? Simple way to understand Encapsulation and Abstraction Difference between Encapsulation and Abstraction How to access private data members outside the class without making "friend"s? Set and Get Methods in java? Good way to encapsulate Integer.parseInt() Difference between private, public, and protected inheritance Difference between abstraction and encapsulation? Why are Python's 'private' methods not actually private?

Examples related to abstraction

What's the difference between abstraction and encapsulation? How abstraction and encapsulation differ? Simple way to understand Encapsulation and Abstraction Difference between Encapsulation and Abstraction Why use getters and setters/accessors? Difference between abstraction and encapsulation? Abstraction VS Information Hiding VS Encapsulation