[oop] What's the difference between abstraction and encapsulation?

In interviews I have been asked to explain the difference between abstraction and encapsulation. My answer has been along the lines of

  • Abstraction allows us to represent complex real world in simplest manner. It is the process of identifying the relevant qualities and behaviors an object should possess; in other words, to represent the necessary feature without representing the background details.

  • Encapsulation is a process of hiding all the internal details of an object from the outside real world. The word "encapsulation", is like "enclosing" into a "capsule". It restricts clients from seeing its internal view where the behavior of the abstraction is implemented.

I think with above answer the interviewer was convinced, but then I was asked, if the purpose of both is hiding, then why there is a need to use encapsulation. At that time I didn't have a good answer for this.

What should I have added to make my answer more complete?

This question is related to oop encapsulation abstraction

The answer is


Abstraction: Hiding the data. Encapsulation: Binding the data.


Encapsulation

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.

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

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 the scenario where 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 by encapsulation.

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.

Read more on this here


Abstraction: In case of an hardware abstraction layer, you have simple interfaces to trigger the hardware (e.g. turn enginge left/right) without knowing the hardware details behind. So hiding the complexity of the system. It's a simplified view of the real world.

Encapsulation: Hiding of object internals. The object is an abstraction of the real world. But the details of this object (like data structures...) can be hidden via encapsulation.


ABSTRACTION:"A view of a problem that extracts the essential information relevant to a particular purpose and ignores the remainder of the information."[IEEE, 1983]

ENCAPSULATION: "Encapsulation or equivalently information hiding refers to the practice of including within an object everything it needs, and furthermore doing this in such a way that no other object need ever be aware of this internal structure."


Encapsulation : Suppose I have some confidential documents, now I hide these documents inside a locker so no one can gain access to them, this is encapsulation.

Abstraction : A huge incident took place which was summarised in the newspaper. Now the newspaper only listed the more important details of the actual incident, this is abstraction. Further the headline of the incident highlights on even more specific details in a single line, hence providing higher level of abstraction on the incident. Also highlights of a football/cricket match can be considered as abstraction of the entire match.

Hence encapsulation is hiding of data to protect its integrity and abstraction is highlighting more important details.

In programming terms we can see that a variable may be enclosed is the scope of a class as private hence preventing it from being accessed directly from outside, this is encapsulation. Whereas a a function may be written in a class to swap two numbers. Now the numbers may be swapped in either by either using a temporary variable or through bit manipulation or using arithmetic operation, but the goal of the user is to receive the numbers swapped irrespective of the method used for swapping, this is abstraction.


Encapsulation is basically denying the access to the internal implementation or knowledge about internals to the external world, while Abstraction is giving a generalized view of any implementation that helps the external world to interact with it


Why Encapsulation? Why Abstraction?

lets start with the question below:

1)What happens if we allow code to directly access field ? (directly allowing means making field public)

lets understand this with an example,

following is our BankAccount class and following is its limitation
*Limitation/Policy* : Balance in BankAccount can not be more than 50000Rs. (This line 
 is very important to understand)

class BankAccount
{
   **public** double balanceAmount;
}

Following is **AccountHolder**(user of BankAccount) class which is consumer of 
**BankAccount** class.

class AccountHolder
{
   BankAccount mybankAccount = new BankAccount();

   DoAmountCreditInBankAccount()
   {
       mybankAccount.balanceAmount = 70000; 
      /* 
       this is invalid practice because this statement violates policy....Here 
       BankAccount class is not able to protect its field from direct access
       Reason for direct access by acount holder is that balanceAmount directly 
       accessible due to its public access modifier. How to solve this issue and 
       successfully implement BankAccount Policy/Limitation. 
      */
   }
}

if some other part of code directly access balanceAmount field and set balance amount to 70000Rs which is not acceptable. Here in this case we can not prevent some other part of code from accessing balanceAmount field.

So what we can do?

=> Answer is we can make balanceAmount field private so that no other code can directly access it and allowing access to that field only via public method which operates on balanceAmount field. Main role of method is that we can write some prevention logic inside method so that field can not be initialized with more than 50000Rs. Here we are making binding between data field called balanceAmount and method which operates on that field. This process is called Encapsulation.(it is all about protecting fields using access modifier such as private)

Encapsulation is one way to achieve abstraction....but How? => User of this method will not know about implementation (How amount gets credited? logic and all that stuff) of method which he/she will invoke. Not knowing about implementation details by user is called Abstraction(Hiding details from user).

Following will be the implementation of class:

class BankAccount
{
   **private** double balanceAmount;

   **public** void UpdateBankBalance(double amount)
   {
    if(balanceAmount + amount > 50000)
    {
       Console.WriteLine("Bank balance can not be more than 50000, Transaction can 
                          not be proceed");
    }
    else
    {
       balanceAmount = balanceAmount + amount;
           Console.WriteLine("Amount has been credited to your bank account 
                              successfully.....");
    }
   }
}


class AccountHolder
{
   BankAccount mybankAccount = new BankAccount();

   DoAmountCreditInBankAccount()
   {
      mybankAccount.UpdateBankBalance(some_amount);
      /*
       mybankAccount.balanceAmount will not be accessible due to its protection level 
       directly from AccountHolder so account holder will consume BankAccount public 
       method UpdateBankBalance(double amount) to update his/her balance.
      */
   }
}

Developer A, who is inherently utilising the concept of abstraction will use a module/library function/widget, concerned only with what it does (and what it will be used for) but not how it does it. The interface of that module/library function/widget (the 'levers' the Developer A is allowed to pull/push) is the personification of that abstraction.

Developer B, who is seeking to create such a module/function/widget will utilise the concept of encapsulation to ensure Developer A (and any other developer who uses the widget) can take advantage of the resulting abstraction. Developer B is most certainly concerned with how the widget does what it does.

TLDR;

  • Abstraction - I care about what something does, but not how it does it.
  • Encapsulation - I care about how something does what it does such that others only need to care about what it does.

(As a loose generalisation, to abstract something, you must encapsulate something else. And by encapsulating something, you have created an abstraction.)


In my view encapsulation is a thought of programmer to hide the complexity of the program code by using access specifier.
Where as Abstraction is separation of method and object according to there function and behavior. For example Car has sheets, wheels, break, headlight.


Abstraction

Exposing the Entity instead of the details of the entity.

"Details are there, but we do not consider them. They are not required."

Example 1:

Various calculations: Addition, Multiplication, Subtraction, Division, Square, Sin, Cos, Tan.

We do not show the details of how do we calculate the Sin, Cos or Tan. We just Show Calculator and it's various Methods which will be, and which needs to be used by the user.

Example 2:

Employee has: First Name, Last Name, Middle Name. He can Login(), Logout(), DoWork().

Many processes might be happening for Logging employee In, such as connecting to database, sending Employee ID and Password, receiving reply from Database. Although above details are present, we will hide the details and expose only "Employee".

Encapsulation

Enclosing. Treating multiple characteristics/ functions as one unit instead of individuals. So that outside world will refer to that unit instead of it's details directly.

"Details are there, we consider them, but do not show them, instead we show what you need to see."

Example 1:

Instead of calling it as Addition, Subtraction, Multiplication, Division, Now we will call it as a Calculator.

Example 2:

All characteristics and operations are now referred by the employee, such as "John". John Has name. John Can DoWork(). John can Login().

Hiding

Hiding the implemention from outside world. So that outside world will not see what should not be seen.

"Details are there, we consider them, but we do not show them. You do not need to see them."

Example 1:

Your requirement: Addition, Substraction, Multiplication, Division. You will be able to see it and get the result.

You do not need to know where operands are getting stored. Its not your requirement.

Also, every instruction that I am executing, is also not your requirement.

Example 2:

John Would like to know his percentage of attendance. So GetAttendancePercentage() Will be called.

However, this method needs data saved in database. Hence it will call FetchDataFromDB(). FetchDataFromDB() is NOT required to be visible to outside world.

Hence we will hide it. However, John.GetAttendancePercentage() will be visible to outside world.

Abstraction, encapsulation and hiding complement each others.

Because we create level of abstraction over details, the details are encapsulated. And because they are enclosed, they are hidden.


Encapsulation is used for 2 main reasons:

1.) Data hiding & protecting (the user of your class can't modify the data except through your provided methods).

2.) Combining the data and methods used to manipulate the data together into one entity (capsule). I think that the second reason is the answer your interviewer wanted to hear.

On the other hand, abstraction is needed to expose only the needed information to the user, and hiding unneeded details (for example, hiding the implementation of methods, so that the user is not affected if the implementation is changed).


I know there are lot's of answers before me with variety of examples.
Well here is my opinion abstraction is getting interested from reality .

In abstraction we hide something to reduce the complexity of it and In encapsulation we hide something to protect the data.

So we define encapsulation as wrapping of data and methods in single entity referred as class.

In java we achieve encapsulation using getters and setters not just by wrapping data and methods in it. we also define a way to access that data. and while accessing data we protect it also.

Techinical e.g would be to define a private data variable call weight.Now we know that weight can't be zero or less than zero in real world scenario.
Imagine if there are no getters and setters someone could have easily set it to a negative value being public member of class.

Now final difference using one real world example,
Consider a circuit board consisting of switches and buttons. We wrap all the wires into a a circuit box, so that we can protect someone by not getting in contact directly(encapsulation).

We don't care how those wires are connected to each other we just want an interface to turn on and off switch. That interface is provided by buttons(abstraction)


A program has mainly two parts : DATA and PROCESS. abstraction hides data in process so that no one can change. Encapsulation hides data everywhere so that it cannot be displayed. I hope this clarifies your doubt.


Difference between Abstraction and Encapsulation :-

Abstraction

  1. Abstraction solves the problem in the design level.
  2. Abstraction is used for hiding the unwanted data and giving relevant data.
  3. Abstraction lets you focus on what the object does instead of how it does it.
  4. Abstraction- Outer layout, used in terms of design. For Example:- Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number.

Encapsulation

  1. Encapsulation solves the problem in the implementation level.
  2. Encapsulation means hiding the code and data into a single unit to protect the data from outside world.
  3. Encapsulation means hiding the internal details or mechanics of how an object does something.
  4. Encapsulation- Inner layout, used in terms of implementation. For Example:- Inner Implementation detail of a Mobile Phone, how keypad button and Display Screen are connect with each other using circuits.

Abstraction is one of the many benefits of Data Encapsulation. We can also say Data Encapsulation is one way to implement Abstraction.


Abstraction : Abstraction is process in which you collect or gather relevant data and remove non-relevant data. (And if you have achieved abstraction, then encapsulation also achieved.)

Encapsulation: Encapsulation is a process in which you wrap of functions and members in a single unit. Means You are hiding the implementation detail. Means user can access by making object of class, he/she can't see detail.

Example:

 public class Test
   {
    int t;
    string  s;
 public void show()
  {
   s = "Testing";
   Console.WriteLine(s);
   Console.WriteLine(See()); // No error
  }

 int See()
  {
   t = 10;
   return t;
  }

 public static void Main()
  {
  Test obj =  new Test();
  obj.Show(); // there is no error
  obj.See(); // Error:- Inaccessible due to its protection level
  }
 }

In the above example, User can access only Show() method by using obj, that is Abstraction.

And See() method is calling internally in Show() method that is encapsulation, because user doesn't know what things are going on in Show() method.


My opinion of abstraction is not in the sense of hiding implementation or background details!

Abstraction gives us the benefit to deal with a representation of the real world which is easier to handle, has the ability to be reused, could be combined with other components of our more or less complex program package. So we have to find out how we pick a complete peace of the real world, which is complete enough to represent the sense of our algorithm and data. The implementation of the interface may hide the details but this is not part of the work we have to do for abstracting something.

For me most important thing for abstraction is:

  1. reduction of complexity
  2. reduction of size/quantity
  3. splitting of non related domains to clear and independent components

All this has for me nothing to do with hiding background details!

If you think of sorting some data, abstraction can result in:

  1. a sorting algorithm, which is independent of the data representation
  2. a compare function, which is independent of data and sort algorithm
  3. a generic data representation, which is independent of the used algorithms

All these has nothing to do with hiding information.


As far as iOS is concerned, it can be said that Objective C files (i.e. .h and .m) use abstraction as well as encapsulation.

Abstraction

Header file (.h) only exposes the functions and public members to outside world. No one knows how they are used unless they have the implementation file with them. It is the .m file that holds all the usage and implementation logic with it self. "Implementation remains unexposed".

Encapsulation

The property (@property) encapsulates the memory management attribute (atomic, strong, retain, weak) of an iVar.


The essential thing about abstraction is that client code operates in terms of a different logical/abstract model. That different model may be more or less complex than the implementation happens to be in any given client usage.

For example, "Iterator" abstracts (aka generalises) sequenced traversal of 0 or more values - in C++ it manifests as begin(), */-> (dereferencing), end(), pre/post ++ and possibly --, then there's +, +=, [], std::advance etc.. That's a lot of baggage if the client could say increment a size_t along an array anyway. The essential thing is that the abstraction allows client code that needs to perform such a traversal to be decoupled from the exact nature of the "container" or data source providing the elements. Iteration is a higher-level notion that sometimes restricts the way the traversal is performed (e.g. a forward iterator can only advance an element at a time), but the data can then be provided by a larger set of sources (e.g. from a keyboard where there's not even a "container" in the sense of concurrently stored values). The client code can generally switch to another data source abstracted through its own iterators with minimal or even no changes, and even polymorphically to other data types - either implicitly or explicitly using something like std::iterator_traits<Iterator>::value_type available.

This is quite a different thing from encapsulation, which is the practice of making some data or functions less accessible, such that you know they're only used indirectly as a result of operations on the public interface. Encapsulation is an essential tool for maintaining invariants on an object, which means things you want to keep true after every public operation - if client code could just reach in and modify your object then you can't enforce any invariants. For example, a class might wrap a string, ensuring that after any operation any lowercase letters were changed to upper case, but if the client code can reach in and put a lowercase letter into the string without the involvement of the class's member functions, then the invariant can't be enforced.

To further highlight the difference, consider say a private std::vector<Timing_Sample> data member that's incidentally populated by operations on the containing object, with a report dumped out on destruction. With the data and destructor side effect not interacting with the object's client code in any way, and the operations on the object not intentionally controlling the time-keeping behaviour, there's no abstraction of that time reporting functionality but there is encapsulation. An example of abstraction would be to move the timing code into a separate class that might encapsulate the vector (make it private) and just provide a interface like add(const Timing_Sample&) and report(std::ostream&) - the necessary logical/abstract operations involved with using such instrumentation, with the highly desirable side effect that the abstracted code will often be reusable for other client code with similar functional needs.


Simply put, abstraction is all about making necessary information for interaction with the object visible, while encapsulation enables a developer to implement the desired level of abstraction.


In my opinion, both terms are related in some sense and sort of mixed into each other. "Encapsulation" provides a way to grouping related fields, methods in a class (or module) to wrap the related things together. As of that time, it provides data hiding in two ways;

  1. Through access modifiers.

    Purely for hiding state of the class/object.

  2. Abstracting some functionalities.

    a. Through interfaces/abstract classes, complex logic inside the encapsulated class or module can be abstracted/generalized to be used by outside.

    b. Through function signatures. Yes, even function signatures example of abstracting. Because callers only knows the signature and parameters (if any) and know nothing about how the function is carried out. It only cares of returned value.

Likewise, "Abstraction" might be think of a way of encapsulation in terms of grouping/wrapping the behaviour into an interface (or abstract class or might be even a normal class ).


Abstraction refers to the act of representing essential features without including the background details or explanations.

Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.

Difference between abstraction and encapsulation

1.Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.

2.Abstraction solves the problem in the design side while Encapsulation is the Implementation.

3.Encapsulation is the deliverable of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.


Its Simple!

Take example of television - it is Encapsulation, because:

  1. Television is loaded with different functionalies that i don't know because they are completely hidden.

  2. Hidden things like music, video etc everything bundled in a capsule that what we call a TV

Now, Abstraction is When we know a little about something and which can help us to manipulate something for which we don't know how it works internally.

For eg: A remote-control for TV is abstraction, because

  1. With remote we know that pressing the number keys will change the channels. We are not aware as to what actually happens internally. We can manipulate the hidden thing but we don't know how it is being done internally.

Programmatically, when we can acess the hidden data somehow and know something.. is Abstraction .. And when we know nothing about the internals its Encapsulation.

Without remote we can't change anything on TV we have to see what it shows coz all controls are hidden.


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