[oop] Difference between abstraction and encapsulation?

What is the precise difference between encapsulation and abstraction?

This question is related to oop encapsulation abstraction

The answer is


encapsulation puts some things in a box and gives you a peephole; this keeps you from mucking with the gears.

abstraction flat-out ignores the details that don't matter, like whether the things have gears, ratchets, flywheels, or nuclear cores; they just "go"

examples of encapsulation:

  • underpants
  • toolbox
  • wallet
  • handbag
  • capsule
  • frozen carbonite
  • a box, with or without a button on it
  • a burrito (technically, the tortilla around the burrito)

examples of abstraction:

  • "groups of things" is an abstraction (which we call aggregation)
  • "things that contains other things" is an abstraction (which we call composition)
  • "container" is another kind of "things that contain other things" abstraction; note that all of the encapsulation examples are kinds of containers, but not all containers exhibit/provide encapsulation. A basket, for example, is a container that does not encapsulate its contents.

Abstraction

Abstraction is the process of extracting out the common properties and fields of all existing and foreseen implementations.

For example: Car is an abstraction for Sedan, Hatchback, SUV, Coupe, Convertible. Car would have all the properties and fields common to all types of cars.

Encapsulation

Encapsulation is the process of hiding unwanted details from the user. This term comes from the Capsule. Just like medicine is hidden from the user inside the capsule. Details of various machines and equipments and devices ranging from Mixers, Bikes, Washing machines, Radio, Television to Airplanes. You don't want all the details of the machine to be visible to user.

In programming terms: Let us consider a class Car. In the example below, all that user needs to know is turn the key (turnKey() method), he does not know about the internal functions. User does not need to know about any of the internal functions or about the internal components.

In this case, all the private methods are internal functions and private fields like 'Piston p1' are internal data which user does not need to know.

public class Car{

    private void startMotor(){ //do something }
    private void generateVoltage(){ //do something }
    private void sparkPlugIgnition(){ //do something }
    private void fuelFlowFromTankToInjector(){ //do something }
    private void pushPistonsDown() { 
               p1.doAction();
               p2.doAction();
               //do something    }
    private void moveCrankShaft(){ //do something }

    private Piston p1;
    private Piston p2;

    public void turnKey(){
        startMotor();
        generateVoltage();
        sparkPlugIgnition();
        fuelFlowFromTankToInjector();
        pushPistonsDown();
        moveCrankShat();
        ...
    }
}

Abstraction--- Hiding Implementation--at Design---Using Interface/Abstract calsses

Encapsulation--Hiding Data --At Development---Using access modifiers(public/private)


From this

Difference between Encapsulation and Abstraction in OOPS

Abstraction and Encapsulation are two important Object Oriented Programming (OOPS) concepts. Encapsulation and Abstraction both are interrelated terms.

Real Life Difference Between Encapsulation and Abstraction

Encapsulate means to hide. Encapsulation is also called data hiding.You can think Encapsulation like a capsule (medicine tablet) which hides medicine inside it. Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation.

Abstraction refers to showing only the necessary details to the intended user. As the name suggests, abstraction is the "abstract form of anything". We use abstraction in programming languages to make abstract class. Abstract class represents abstract view of methods and properties of class.

Implementation Difference Between Encapsulation and Abstraction

  1. Abstraction is implemented using interface and abstract class while Encapsulation is implemented using private and protected access modifier.

  2. OOPS makes use of encapsulation to enforce the integrity of a type (i.e. to make sure data is used in an appropriate manner) by preventing programmers from accessing data in a non-intended manner. Through encapsulation, only a predetermined group of functions can access the data. The collective term for datatypes and operations (methods) bundled together with access restrictions (public/private, etc.) is a class.


Let's take the example of a stack. It could be implemented using an array or a linked list. But the operations it supports are push and pop.

Now abstraction is exposing only the interfaces push and pop. The underlying representation is hidden (is it an array or a linked list?) and a well-defined interface is provided. Now how do you ensure that no accidental access is made to the abstracted data? That is where encapsulation comes in. For example, classes in C++ use the access specifiers which ensure that accidental access and modification is prevented. And also, by making the above-mentioned interfaces as public, it ensures that the only way to manipulate the stack is through the well-defined interface. In the process, it has coupled the data and the code that can manipulate it (let's not get the friend functions involved here). That is, the code and data are bonded together or tied or encapsulated.


Encapsulation require modularity. It requires you to create objects that has the data and the methods to process the data. In this case you can view it as a module.

Abstraction provides you a generalized view of your classes.


Encapsulation is hiding the implementation details which may or may not be for generic or specialized behavior(s).

Abstraction is providing a generalization (say, over a set of behaviors).

Here's a good read: Abstraction, Encapsulation, and Information Hiding by Edward V. Berard of the Object Agency.


There are differences between

ABSTRAACTION

and

ENCAPSULATION

1.    First difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.

2.    Data abstraction simply means generalizing something to hide the complex logic that goes underneath where Encapsulation is DATA HIDING.


3.    Encapsulation is combining related logic data (variables and methods) where as Abstraction is hiding internal implementation details and expose only relevant details to the user. In a way you can Abstraction is achieved by Encapsulation.

enter image description here


Most answers here focus on OOP but encapsulation begins much earlier:

  • Every function is an encapsulation; in pseudocode:

    point x = { 1, 4 }
    point y = { 23, 42 }
    
    numeric d = distance(x, y)
    

    Here, distance encapsulates the calculation of the (Euclidean) distance between two points in a plane: it hides implementation details. This is encapsulation, pure and simple.

  • Abstraction is the process of generalisation: taking a concrete implementation and making it applicable to different, albeit somewhat related, types of data. The classical example of abstraction is C’s qsort function to sort data:

    The thing about qsort is that it doesn't care about the data it sorts — in fact, it doesn’t know what data it sorts. Rather, its input type is a typeless pointer (void*) which is just C’s way of saying “I don't care about the type of data” (this is also called type erasure). The important point is that the implementation of qsort always stays the same, regardless of data type. The only thing that has to change is the compare function, which differs from data type to data type. qsort therefore expects the user to provide said compare function as a function argument.

Encapsulation and abstraction go hand in hand so much so that you could make the point that they are truly inseparable. For practical purposes, this is probably true; that said, here’s an encapsulation that’s not much of an abstraction:

class point {
    numeric x
    numeric y
}

We encapsulate the point’s coordinate, but we don’t materially abstract them away, beyond grouping them logically.

And here’s an example of abstraction that’s not encapsulation:

T pi<T> = 3.1415926535

This is a generic variable pi with a given value (p), and the declaration doesn’t care about the exact type of the variable. Admittedly, I’d be hard-pressed to find something like this in real code: abstraction virtually always uses encapsulation. However, the above does actually exist in C++(14), via variable templates (= generic templates for variables); with a slightly more complex syntax, e.g.:

template <typename T> constexpr T pi = T{3.1415926535};

Abstraction is generalised term. i.e. Encapsulation is subset of Abstraction.

enter image description here

  • Example 2:
    The solution architect is the person who creates the high-level abstract technical design of the entire solution, and this design is then handed over to the the development team for implementation.

    Here, solution architect acts as a abstract and development team acts as a Encapsulation.

  • Example 3: Encapsulation(networking) of user data

enter image description here

Courtesy

Abstraction (or modularity) – Types enable programmers to think at a higher level than the bit or byte, not bothering with low-level implementation. For example, programmers can begin to think of a string as a set of character values instead of as a mere array of bytes. Higher still, types enable programmers to think about and express interfaces between two of any-sized subsystems. This enables more levels of localization so that the definitions required for interoperability of the subsystems remain consistent when those two subsystems communicate. Source


Abstraction and Encapsulation by using a single generalized example

------------------------------------------------------------------------------------------------------------------------------------

We all use calculator for calculation of complex problems !

image


Let me try this with simple code example

Abstraction = Data Hiding + Encapsulation

 // Abstraction
    interface IOperation
    {
        int GetSumOfNumbers();
    }
    internal class OperationEven : IOperation
    {
        // data hiding
        private IEnumerable<int> numbers;

        public OperationEven(IEnumerable<int> numbers)
        {
            this.numbers = numbers;
        }
        // Encapsulation
        public int GetSumOfNumbers()
        {
            return this.numbers.Where(i => i % 2 == 0).Sum();
        }
    }

The below paragraph helped me to understand how they differ from each other:

Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

You can read more here.


I will try to demonstrate Encapsulation in a simple way.. Lets see..

  • The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Encapsulation containing and hiding information about an object, such as internal data structures and code.

Encapsulation is -

  • Hiding Complexity,
  • Binding Data and Function together,
  • Making Complicated Method's Private,
  • Making Instance Variable's Private,
  • Hiding Unnecessary Data and Functions from End User.

Encapsulation implements Abstraction.

And Abstraction is -

  • Showing Whats Necessary,
  • Data needs to abstract from End User,

Lets see an example-

The below Image shows a GUI of "Customer Details to be ADD-ed into a Database".

Customer Screen GUI

By looking at the Image we can say that we need a Customer Class.

Step - 1: What does my Customer Class needs?

i.e.

  • 2 variables to store Customer Code and Customer Name.
  • 1 Function to Add the Customer Code and Customer Name into Database.

    namespace CustomerContent { public class Customer { public string CustomerCode = ""; public string CustomerName = ""; public void ADD() { //my DB code will go here }

Now only ADD method wont work here alone.

Step -2: How will the validation work, ADD Function act?

We will need Database Connection code and Validation Code (Extra Methods).

public bool Validate()
{
    //Granular Customer Code and Name
    return true;
}

public bool CreateDBObject()
{
    //DB Connection Code
    return true;
}


class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;

obj.CustomerCode = "s001";
obj.CustomerName = "Mac";

obj.Validate();
obj.CreateDBObject();

obj.ADD();
}
}

Now there is no need of showing the Extra Methods(Validate(); CreateDBObject() [Complicated and Extra method] ) to the End User.End user only needs to see and know about Customer Code, Customer Name and ADD button which will ADD the record.. End User doesn't care about HOW it will ADD the Data to Database?.

Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction.

So making those Complicated and Extra method as Private instead Public(i.e Hiding those methods) and deleting the obj.Validate(); obj.CreateDBObject(); from main in class Program we achieve Encapsulation.

In other words Simplifying Interface to End User is Encapsulation.

So now the code looks like as below -

namespace CustomerContent
{
public class Customer
{
public string CustomerCode = "";
public string CustomerName = "";
public void ADD()
{
   //my DB code will go here
}

private bool Validate()
{
    //Granular Customer Code and Name
    return true;
}

private bool CreateDBObject()
{
    //DB Connection Code
    return true;
}


class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;

obj.CustomerCode = "s001";

obj.CustomerName = "Mac";

obj.ADD();
}
}

Summary :

Step -1: What does my Customer Class needs? is Abstraction.

Step -3: Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction is Encapsulation.

P.S. - The code above is hard and fast.


abstraction is hiding non useful data from users and encapsulation is bind together data into a capsule (a class). I think encapsulation is way that we achieve abstraction.


Encapsulation: Is hiding unwanted/un-expected/propriety implementation details from the actual users of object. e.g.

List<string> list = new List<string>();
list.Sort(); /* Here, which sorting algorithm is used and hows its 
implemented is not useful to the user who wants to perform sort, that's 
why its hidden from the user of list. */

Abstraction: Is a way of providing generalization and hence a common way to work with objects of vast diversity. e.g.

class Aeroplane : IFlyable, IFuelable, IMachine
{ // Aeroplane's Design says:
  // Aeroplane is a flying object
  // Aeroplane can be fueled
  // Aeroplane is a Machine
}
// But the code related to Pilot, or Driver of Aeroplane is not bothered 
// about Machine or Fuel. Hence,
// pilot code:
IFlyable flyingObj = new Aeroplane();
flyingObj.Fly();
// fighter Pilot related code
IFlyable flyingObj2 = new FighterAeroplane();
flyingObj2.Fly();
// UFO related code 
IFlyable ufoObj = new UFO();
ufoObj.Fly();
// **All the 3 Above codes are genaralized using IFlyable,
// Interface Abstraction**
// Fly related code knows how to fly, irrespective of the type of 
// flying object they are.

// Similarly, Fuel related code:
// Fueling an Aeroplane
IFuelable fuelableObj = new Aeroplane();
fuelableObj.FillFuel();
// Fueling a Car
IFuelable fuelableObj2 = new Car(); // class Car : IFuelable { }
fuelableObj2.FillFuel();

// ** Fueling code does not need know what kind of vehicle it is, so far 
// as it can Fill Fuel**

Encapsulation is wrapping up complexity in one capsule that is class & hence Encapsulation… While abstraction is the characteristics of an object which differentiates from other object...

Abstraction can be achieved by making class abstract having one or more methods abstract. Which is nothing but the characteristic which should be implemented by the class extending it. e.g. when you inventing/designing a car you define a characteristics like car should have 4 doors, break, steering wheel etc… so anyone uses this design should include this characteristics. Implementation is not the head each of abstraction. It will just define characteristics which should be included.

Encapsulation is achieved keeping data and the behaviour in one capsule that is class & by making use of access modifiers like public, private, protected along with inheritance, aggregation or composition. So you only show only required things, that too, only to the extent you want to show. i.e. public, protected, friendly & private ka funda…… e.g. GM decides to use the abstracted design of car above. But they have various products having the same characteristics & doing almost same functionality. So they write a class which extends the above abstract class. It says how gear box should work, how break should work, how steering wheel should work. Then all the products just use this common functionality. They need not know how the gear box works or break works or steering wheal works. Indivisual product can surely have more features like a/c or auto lock etc…..

Both are powerful; but using abstraction require more skills than encapsulation and bigger applications/products can not survive with out abstraction.


Encapsulation means-hiding data like using getter and setter etc.

Abstraction means- hiding implementation using abstract class and interfaces etc.


These are somewhat fuzzy concepts that are not unique to Computer Science and programming. I would like to offer up some additional thoughts that may help others understand these important concepts.


Short Answer

Encapsulation - Hiding and/or restricting access to certain parts of a system, while exposing the necessary interfaces.

Abstraction - Considering something with certain characteristics removed, apart from concrete realities, specific objects, or actual instances, thereby reducing complexity.

The main similarity is that these techniques aim to improve comprehension and utility.

The main difference is that abstraction is a means of representing things more simply (often to make the representation more widely applicable), whereas encapsulation is a method of changing the way other things interact with something.


Long Answer

Encapsulation

Here's an example of encapsulation that hopefully makes things more clear:

Arduino Encapsulation

Here we have an Arduino Uno, and an Arduino Uno within an enclosure. An enclosure is a great representation of what encapsulation is all about.

Encapsulation aims to protect certain components from outside influences and knowledge as well as expose components which other things should interface with. In programming terms, this involves information hiding though access modifiers, which change the extent to which certain variables and/or properties can be read and written.

But beyond that, encapsulation also aims to provide those external interfaces much more effectively. With our Arduino example, this could include the nice buttons and screen which makes the user's interaction with the device much simpler. They provide the user with simple ways to affect the device's behavior and gain useful information about its operation which would otherwise be much more difficult.

In programming, this involves the grouping of various components into a separable construct, such as a function, class, or object. It also includes providing the means of interacting with those constructs, as well as methods for gaining useful information about them.

Encapsulation helps programmers in many many additional ways, not least of which is improved code maintainability and testability.

Abstraction

Although many other answers here defined abstraction as generalization, I personally think that definition is misguided. I would say that generalization is actually a specific type of abstraction, not the other way around. In other words, all generalizations are abstractions, but all abstractions are not necessarily generalizations.

Here's how I like to think of abstraction:

Pixel Tree

Would you say the image there is a tree? Chances are you would. But is it really a tree? Well, of course not! It's a bunch of pixels made to look like something we might call a tree. We could say that it represents an abstraction of a real tree. Notice that several visual details of the tree are omitted. Also, it does not grow, consume water, or produce oxygen. How could it? it's just a bunch of colors on a screen, represented by bytes in your computer memory.

And here is the essence of abstraction. It's a way of simplifying things so they are easier to understand. Every idea going through your head is an abstraction of reality. Your mental image of a tree is no more an actual tree than this jpeg is.

In programming, we might use this to our advantage by creating a Tree class with methods for simulated growing, water consuming, and oxygen production. Our creation would be something that represents our experience of actual trees, and only includes those elements that we really care about for our particular simulation. We use abstraction as a way of representing our experience of something with bytes and mathematics.

Abstract Classes

Abstraction in programming also allows us to consider commonalities between several "concrete" object types (types that actually exist) and define those commonalities within a unique entity. For example, our Tree class may inherit from an abstract class Plant, which has several properties and methods which are applicable to all of our plant-like classes, but removes those that are specific to each type of plant. This can significantly reduce duplication of code, and improves maintainability.

The practical difference of an abstract class and plain class is that conceptually there's no "real" instances of the abstract class. It wouldn't make sense to construct a Plant object because that's not specific enough. Every "real" Plant is also a more specific type of Plant.

Also, if we want our program to be more realistic, we might want to consider the fact that our Tree class might be too abstract itself. In reality, every Tree is a more specific type of Tree, so we could create classes for those types such as Birch, Maple, etc. which inherit from our, perhaps now abstract, Tree class.

JVM

Another good example of abstraction is the Java Virtual Machine (JVM), which provides a virtual or abstract computer for Java code to run on. It essentially takes away all of the platform specific components of a system, and provides an abstract interface of "computer" without regard to any system in particular.

The Difference

Encapsulation differs from abstraction in that it doesn't have anything to do with how 'real' or 'accurate' something is. It doesn't remove components of something to make it simpler or more widely applicable. Rather it may hide certain components to achieve a similar purpose.


class Aeroplane : IFlyable, IFuelable, IMachine
{ // Aeroplane's Design says:
  // Aeroplane is a flying object
  // Aeroplane can be fueled
  // Aeroplane is a Machine
}
// But the code related to Pilot, or Driver of Aeroplane is not bothered 
// about Machine or Fuel. Hence,
// pilot code:
IFlyable flyingObj = new Aeroplane();
flyingObj.Fly();
// fighter Pilot related code
IFlyable flyingObj2 = new FighterAeroplane();
flyingObj2.Fly();
// UFO related code 
IFlyable ufoObj = new UFO();
ufoObj.Fly();
// **All the 3 Above codes are genaralized using IFlyable,
// Interface Abstraction**
// Fly related code knows how to fly, irrespective of the type of 
// flying object they are.

// Similarly, Fuel related code:
// Fueling an Aeroplane
IFuelable fuelableObj = new Aeroplane();
fuelableObj.FillFuel();
// Fueling a Car
IFuelable fuelableObj2 = new Car(); // class Car : IFuelable { }
fuelableObj2.FillFuel();

// ** Fueling code does not need know what kind of vehicle it is, so far 
// as it can Fill Fuel**

I Think Encapsulation is a way to implement abstraction. Have a look at the following link.

Abstraction and Encapsulation


The process of Abstraction and Encapsulation both generate interfaces.

An interface generated via encapsulation hides implementation details.

An interface generated via abstraction becomes applicable to more data types, compared to before abstraction.


Difference Between Abstraction and Encapsulation.

Difference between Abstraction and Encapsulation


Another example:

Suppose I created an immutable Rectangle class like this:

class Rectangle {
 public:
  Rectangle(int width, int height) : width_(width), height_(height) {}
  int width() const { return width_; }
  int height() const { return height_; }

 private:
  int width_;
  int height_;
}

Now it's obvious that I've encapsulated width and height (access is somehow restricted), but I've not abstracted anything (okay, maybe I've ignored where the rectangle is located in the coordinates space, but this is a flaw of the example).

Good abstraction usually implies good encapsulation.

An example of good abstraction is a generic database connection class. Its public interface is database-agnostic, and is very simple, yet allows me to do what I want with the connection. And you see? There's also encapsulation there, because the class must have all the low-level handles and calls inside.


I try to draw a line here between abstraction and encapsulation, according to me Abstraction is more of conceptual thing where as encapsulation is one of the abstraction implementation. Since one can hide data without encapsulation, for instance using private constants or variables; so we can have encapsulation with data hiding but data hiding is not always encapsulation. In below piece of code I try to depict simplest form of these concepts.

    // Abstraction
    interface IOperation
    {
        int SquareNumber();
    }

    public class Operation
    {
        // Data hiding
        private int number;

        public Operation(int _number)
        {
            this.number = _number;
        }

        // Encapsulation
        public int SquareNumber()
        {
            return number * number;
        }
    }

In action,

IOperation obj = new Operation(2); 
// obj.number  <--- can't access because hidden from world using private access modifier but not encapsulated. 
obj.SquareNumber(); // cannot access internal logic to calculate square because logic is hidden using encapsulation.

A lot of good answers are provided above but I am going to present my(Java) viewpoint here.

Data Encapsulation simply means wrapping and controlling access of logically grouped data in a class. It is generally associated with another keyword - Data Hiding. This is achieved in Java using access modifiers.

A simple example would be defining a private variable and giving access to it using getter and setter methods or making a method private as it's only use is withing the class. There is no need for user to know about these methods and variables.

Note : It should not be misunderstood that encapsulation is all about data hiding only. When we say encapsulation, emphasis should be on grouping or packaging or bundling related data and behavior together.

Data Abstraction on the other hand is concept of generalizing so that the underneath complex logic is not exposed to the user. In Java this is achieved by using interfaces and abstract classes.

Example -

Lets say we have an interface Animal and it has a function makeSound(). There are two concrete classes Dog and Cat that implement this interface. These concrete classes have separate implementations of makeSound() function. Now lets say we have a animal(We get this from some external module). All user knows is that the object that it is receiving is some Animal and it is the users responsibility to print the animal sound. One brute force way is to check the object received to identify it's type, then typecast it to that Animal type and then call makeSound() on it. But a neater way is to abstracts thing out. Use Animal as a polymorphic reference and call makeSound() on it. At runtime depending on what the real Object type is proper function will be invoked.

More details here.

enter image description here

Complex logic is in the circuit board which is encapsulated in a touchpad and a nice interface(buttons) is provided to abstract it out to the user.

PS: Above links are to my personal blog.


Abstraction and Encapsulation both are know for data hiding. But there is big difference.

Encapsulation

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single unit called Class.

Encapsulation solves the problem at implementation level.

In class, you can hide data by using private or protected access modifiers.

Abstraction

Abstraction is the concept of hiding irrelevant details. In other words make complex system simple by hiding the unnecessary detail from the user.

Abstraction solves the problem at design level.

You can achieve abstraction by creating interface and abstract class in Java.

In ruby you can achieve abstraction by creating modules.

Ex: We use (collect, map, reduce, sort...) methods of Enumerable module with Array and Hash in ruby.


  • Abstraction lets you focus on what the object does instead of how it does it
  • Encapsulation means hiding the internal details or mechanics of how an object does something.

Like when you drive a car, you know what the gas pedal does but you may not know the process behind it because it is encapsulated.

Let me give an example in C#. Suppose you have an integer:

int Number = 5;
string aStrNumber = Number.ToString();

you can use a method like Number.ToString() which returns you characters representation of the number 5, and stores that in a string object. The method tells you what it does instead of how it does it.


Information hiding is not strictly required for abstraction or encapsulation. Information might be ignored, but does not have to be hidden.

Encapsulation is the ability to treat something as a single thing, even though it may be composed of many complex parts or ideas. For example, I can say that I'm sitting in a "chair" rather than referring to the many various parts of that chair each with a specific design and function, all fitting together precisely for the purpose of comfortably holding my butt a few feet away from the floor.

Abstraction is enabled by encapsulation. Because we encapsulate objects, we can think about them as things which relate to each other in some way rather than getting bogged down in the subtle details of internal object structure. Abstraction is the ability to consider the bigger picture, removed from concern over little details. The root of the word is abstract as in the summary that appears at the top of a scholarly paper, not abstract as in a class which can only be instantiated as a derived subclass.

I can honestly say that when I plop my butt down in my chair, I never think about how the structure of that chair will catch and hold my weight. It's a decent enough chair that I don't have to worry about those details. So I can turn my attention toward my computer. And again, I don't think about the component parts of my computer. I'm just looking at a part of a webpage that represents a text area that I can type in, and I'm communicating in words, barely even thinking about how my fingers always find the right letters so quickly on the keyboard, and how the connection is ultimately made between tapping these keys and posting to this forum. This is the great power of abstraction. Because the lower levels of the system can be trusted to work with consistency and precision, we have attention to spare for greater work.


In short:

Abstraction is a technique that helps us identify which specific information is essential, and which information should be hidden.

Encapsulation is then the technique for enclosing the information in such a way to hide details and implementation details of an object.


In-short

Abstraction use -> Encapsulation & Encapsulation use -> data hiding

OR

data hiding is a subset of Encapsulation and Encapsulation is a subset of Abstraction

Reference: http://www.tonymarston.co.uk/php-mysql/abstraction.txt


Abstraction: The idea of presenting something in a simplified / different way, which is either easier to understand and use or more pertinent to the situation.

Consider a class that sends an email... it uses abstraction to show itself to you as some kind of messenger boy, so you can call emailSender.send(mail, recipient). What it actually does - chooses POP3 / SMTP, calling servers, MIME translation, etc, is abstracted away. You only see your messenger boy.

Encapsulation: The idea of securing and hiding data and methods that are private to an object. It deals more with making something independent and foolproof.

Take me, for instance. I encapsulate my heart rate from the rest of the world. Because I don't want anyone else changing that variable, and I don't need anyone else to set it in order for me to function. Its vitally important to me, but you don't need to know what it is, and you probably don't care anyway.

Look around you'll find that almost everything you touch is an example of both abstraction and encapsulation. Your phone, for instance presents to you the abstraction of being able to take what you say and say it to someone else - covering up GSM, processor architecture, radio frequencies, and a million other things you don't understand or care to. It also encapsulates certain data from you, like serial numbers, ID numbers, frequencies, etc.

It all makes the world a nicer place to live in :D


Many answers and their examples are misleading.

Encapsulation is the packing of data and functions operating on that data into a single component and restricting the access to some of the object's components.
Encapsulation means that the internal representation of an object is generally hidden from view outside of the object's definition.

Abstraction is a mechanism which represent the essential features without including implementation details.

Encapsulation:-- Information hiding.
Abstraction:-- Implementation hiding.

Example:

class foo{
    private:
        int a, b;
    public:
        foo(int x=0, int y=0): a(x), b(y) {}

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

Internal representation of any object of foo class is hidden outside the class. --> Encapsulation.
Any accessible member (data/function) of an object of foo is restricted and can only be accessed by that object only.

foo foo_obj(3, 4);
int sum = foo_obj.add();

Implementation of method add is hidden. --> Abstraction.


Abstraction : Abstraction means to show What part of functionality.

Encapsulation : Encapsulation means to hide the How part of the functionality.

Lets take a very simple example

/// <summary>
/// We have an Employee class having two properties EmployeeName and EmployeeCode
/// </summary>
public class Employee
{
    public string EmplpyeeName { get; set; }
    public string EmployeeCode { get; set; }

    // Add new employee to DB is the main functionality, so are making it public so that we can expose it to external environment
    // This is ABSTRACTION
    public void AddEmployee(Employee obj)
    {
        // "Creation of DB connection" and "To check if employee exists" are internal details which we have hide from external environment
        // You can see that these methods are private, external environment just need "What" part only
        CreateDBConnection();
        CheckIfEmployeeExists();
    }


    // ENCAPLUSATION using private keyword
    private bool CheckIfEmployeeExists()
    {
        // Here we can validate if the employee already exists
        return true;
    }

    // ENCAPLUSATION using private keyword
    private void CreateDBConnection()
    {
        // Create DB connection code
    }
}

Program class of Console Application

class Program
{
    static void Main(string[] args)
    {
        Employee obj = new Employee();
        obj.EmplpyeeName = "001";
        obj.EmployeeCode = "Raj";

        // We have exposed only what part of the functionality
        obj.AddEmployee(obj);
    }
}

Encapsulation is an example of abstraction. The whole point of encapsulation is to abstract what's going on inside the function, to reduce all that complexity to a symbol (the reference or the name of the function), to turn the function into a black box.

In programming, the word "abstract" is a command. When a class inherits an abstract class (or an interface), you are being ordered to create an abstraction.


One thing, perhaps a fundamental thing that other answers forget to mention is that, encapsulation IS abstraction. Therefore, it is not accurate to contrast the two and look for differences, but rather to look at encapsulation as a form of abstraction.


Abstraction is a contract for the implementation we are going to do. Implementation may get changed over period of time. The various implementations themselves may or may not be hidden but are Masked behind the Abstraction.

Suppose we define all the APIs of a class in an interface then ask the users of our code to depened upon the defined APIs of the interface. We are free to improve or modify the implementation only we must follow the set contract. The users are not coupled with our implementation.

We EXPOSE all the NECESSARY Rules (methods) in abstraction, the implementation of the rules are left for the implementor entities, also the implemention is not part of the abstraction. Its just the signature and declaration what makes the abstraction.

Encapsulation is simply HIDING the internal details by reducing the acess of the states and behaviors. An encapsulated class may or may not have well defined Abstraction.

java.util.List is an abstraction for java.util.ArrayList. The internal states of java.util.ArrayList being marked with non public access modifiers is encapsulation.

Edit Suppose a class Container.nava implements IContainer , IContainer may declare methods like addElement, removeElements, contains, etc. Here IContainer represents the abstraction for its implementing class. Abstraction is declaring the APIs of the class or a module or a system to the outer world. These APIs become the contract. That system may be or may not be developed yet. The users of the system now can depend on the declared APIs and are sure any system implementing such a contract will always adhere to the APIs declared, they will always provide tge implementation for those APIs. Once we are writing some concrete entity then deciding to hide our internal states is encapsulation


A mechanism that prevents the data of a particular objects safe from intentional or accidental misuse by external functions is called "data Encapsulation"

The act of representing essential features without including the background details or explanations is known as abstraction


Abstraction: Only necessary information is shown. Let's focus on the example of switching on a computer. The user does not have to know what goes on while the system is still loading (that information is hidden from the user).

Let's take another example, that of the ATM. The customer does not need to know how the machine reads the PIN and processes the transaction, all he needs to do is enter the PIN, take the cash and leave.

Encapsulation: Deals with hiding the sensitive data of a clas hence privatising part of it. It is a way of keeping some information private to its clients by allowing no access to it from outside.


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