Difference between abstraction and encapsulation?
Asked Answered
B

41

455

What is the precise difference between encapsulation and abstraction?

Beachcomber answered 12/4, 2009 at 20:15 Comment(1)
check my answer here. You will get a different view on these concepts https://mcmap.net/q/15787/-difference-between-encapsulation-and-abstractionDulles
I
316

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 (π), 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};
Identity answered 13/4, 2009 at 12:2 Comment(10)
Though every method is an encapsulation, it is also an abstraction, because every time you put some things together and give it a name you create a new (abstract) concept. Encapsulation without abstraction is useless. Therefore it is not true that they've got nothing in common.Italic
@Italic I maintain that the concepts are orthogonal even if their domains overlap. It may even be true that every encapsulation is-an abstraction (although I’m not convinced) – but even then I think that this would be incidental rather than an inherent property of either concept.Identity
They are distinct, but not orthogonal. In fact, I do think that encapsulation is indeed a special kind of abstraction, namely a structural one. By considering something compound as a whole we basically ignore (abstract from) the details of how it is built up of something else, i.e. ignore its internal structure.Italic
Abstraction is when we hide the implementation level details from the user and give access to only necessary values like Sum(1,10) will sum it up. We don't know how. We have abstracted the process of sum from user. Whereas standard definition of encapsulation suggest when we encapsulate i.e. make one data and the method acting on it. Something like class. Binding them into a single entity. The point I am trying to bring here is nothing is a hard line is both need each other to exist. Without one there isn't other.Kleenex
@KonradRudolph can you please tell me how these concepts came into picture? why do we need these concepts(Abstraction and encapsulation )? I've been reading about them for hours now but i'm unable to come to a conclusion. All I find is the "What" not the "Why". Can you please help?Potassium
@psylogic I’m guessing the “why” is skipped because it seems so trivial: without abstraction and encapsulation we couldn’t write complex systems. Even moderately complex problems would require such complex program code that they would fail from the outset. Without abstraction, you couldn’t even write a program to print a number: the concept “print” involves countless abstractions (what’s a screen? what’s a character? what’s a pixel? …)Identity
Can you please update your answer and show one example of Encapsulation which is against/not Abstraction and one example of Abstraction which is against/not Encapsulation.Crackdown
@Crackdown That’s incredibly hard — see discussion in the comments above. However, I’ve added an example that I believe comes close.Identity
Abstraction is the process of generalization, so by making the example more simple can I say Showing only relevant data to mobile a user like screen, camera, speaker User doesn't care about how circuit board of mobile works . Is this example good one ?Timeous
Based on what you explained, it's almost as though abstraction hides the how to do something and encapsulation simply hides the what something contains. Just by the generic concept of 'hiding' things, it is very probable that the set of 'how' to do something, and 'what' something contains coincides with each other, therefore it's reasonable to say encapsulation and abstraction go hand-in-hand, very rare to see mutually exclusive examples of them. I've always prided myself in paraphrasing things to be simpler. Can someone validate my simplification of the concept?Larisalarissa
S
232

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 (in C++):

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 of this 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.

Shrunk answered 24/3, 2015 at 4:4 Comment(10)
Can you please update your answer and show one example of Encapsulation which is against/not Abstraction and one example of Abstraction which is against/not Encapsulation.Crackdown
@bjan; Using qsort function in C is an example of abstraction. You don't know the details of it's implementation. No encapsulation involved here. Using constructors to initialize data fields of an objects in C++ is an example of encapsulation (controlled access of object's component via constructor).Shrunk
"Abstraction:-- Implementation hiding." Hiding the implementation from what?Mccafferty
@ArunRaaj; From other objects which are using it.Shrunk
This should have been marked as the correct answer with some minor editsMacknair
this should be the best answer. simple, clear, and have simple examples along with them.Nitrate
Should this not be the other way around? like: Encapsulation:-- Implementation hiding. Abstraction:-- Information hiding.Allianora
@AdilH.Raza Why should it be like that?Shrunk
would you say every encapsulation is an abstraction but vice versa false?Incarnate
@hafizali Both are different but used together. Abstraction is not encapsulation neither do encapsulation is an abstraction. They are relatable but not same.Shrunk
P
151

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.

Patchy answered 12/4, 2009 at 20:20 Comment(3)
Neha's link also broken now, but yeh. we can always google the article name. this is the one i stumbled upon tonymarston.co.uk/php-mysql/abstraction.txtThomas
Quote that made things clear to me: " Usually, abstraction is not defined in terms of information hiding, e.g., note the use of words such as "ignore" and "extracting." However, we should also note the use of the words "suppress" and "suppressing" in some of the above examples. In short, you might say that abstraction dictates that some information is more important than other information, but (correctly) does not specify a specific mechanism for handling the unimportant information."Alterant
Encapsulation in OOP is not about hiding something. It is about combining state and behaviour together to protect invariants.Biologist
H
116

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.
Hyson answered 12/4, 2009 at 22:10 Comment(11)
Why was this downvoted? It's one of the only correct descriptions in this big sea of wrong answers.Identity
In the encapsulation by only providing the peephole, haven't we ignored the details that don't matter to user- this is what the abstraction is[as said by you]. How the two things are different? May be you can elaborate more.Homey
@Sanjeev encapsulation is concrete, abstraction is...abstract! ;-) encapsulation is an object you can use, abstraction is an ideal you can only discuss. encapsulation is why you wear underwear, abstraction is how you explain the difference between underwear and swimsuitsHyson
@StevenA.Lowe can you please tell me how these concepts came into picture? why do we need these concepts(Abstraction and encapsulation )? I've been reading about them for hours now but i'm unable to come to a conclusion. All I find is "What" not the "Why". Can you please help?Potassium
@psylogic abstraction is how we as thinking beings deal with complexity: we ignore irrelevant details, emphasize relevant common patterns, use symbols as substitutes for real objects, and characterize similar things by how they behave (among other abstraction patterns). Abstraction was not invented by computer science, it is ancient - hieroglyphs are abstractions, words are abstractions, thoughts are abstractions. Encapsulation is likewise ancient (underwear, armor, boxes). You may be trying to make these concepts much harder than they actually are.Hyson
Can you please update your answer and show one example of Encapsulation which is against/not Abstraction and one example of Abstraction which is against/not EncapsulationCrackdown
@bjan: examples added; i hope that helps!Hyson
toolbox, wallet and handbag all contain other things so why these are not abstraction?Crackdown
@bjan: the abstraction would be the concept of "containers"Hyson
Do you mean toolbox, wallet and handbag are not containers!!! I think these are. I am sorry, would you please update examples explaining why these are not containersCrackdown
@bjan: i didn't say they weren't containers; they are. I added some that are less obviously containers, but 'containment' is implied in the notion of encapsulation. "containers" is an abstraction. A basket is a container, but it does not encapsulate (fully cover, hide, protect) its contents. Does that help?Hyson
H
77

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

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

Hames answered 27/11, 2012 at 17:29 Comment(2)
How your answer is related to "Abstraction is the process of generalisation" - How we can achieve generalisation with the help of abstract class and interface. Do you have any example ?Blindfish
Good Answer. IEAPBalustrade
K
67

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

Abstraction Encapsulation
It solves an issue at the design level. Encapsulation solves an issue at implementation level.
hides the unnecessary detail but shows the essential information. It hides the code and data into a single entity or unit so that the data can be protected from the outside world.
Focuses on the external lookout. Focuses on internal working.
Lets focus on what an object does instead of how it does it. Lets focus on how an object does something.
Example: Outer look of mobile, like it has a display screen and buttons. Example: Inner details of mobile, how button and display screen connect with each other using circuits.

Example: 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: Encapsulation(networking) of user data

enter image description here

image 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

Java example

Kindle answered 6/7, 2015 at 10:41 Comment(1)
This is "The Simplest" explanation of all other answers and should have been accepted answer as well.Nutria
S
51

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.

Striation answered 4/1, 2014 at 19:13 Comment(3)
Your blog is too good !! All my oops concepts are completely clear now with applications!Inapprehensible
Best answer so far. Thank you.Miculek
You said in Data abstraction that " the underneath complex logic is not exposed to the user" I have question 1. Who is the user and why are you hiding from the user.Unlimited
C
40

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.

Conceivable answered 26/12, 2015 at 5:16 Comment(0)
D
29
  • 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.

Darden answered 12/4, 2009 at 20:22 Comment(9)
I almost upvoted this for the short, precise answer, but then I saw that car metaphore again which make me puke - Oh well, Im a nice guy :P +1Hogwash
Sorry buddy hehe, I added a better explanation.Darden
So, functions in C also Abstraction?Physiognomy
Abstractions can be built regardless of the language or paradigm being used. In a short answer, YES, there can be abstractions in C. Why not?Darden
Your definitions of both abstraction and encapsulation are same. This is what i understand - how it is done is hidden and what is done is exposed. In your example of car and Number.ToString(), could you precisely point out what is abstraction and encapsulation? This will help in clearing the things.Homey
IMO, information hiding is what you are calling encapsulation. For reference you can see link in this answer. or can refer Encapsulation in javaSnub
@nisargshah95 Yes, so as me, I provided the link to differentiate information hiding and encapsulation. (PS : I am author of that article). It is mentioned in my comment, that it is information hiding not encapsulation.Snub
@KisHanSarsecHaGajjar Sorry, I misread your comment. I withdraw mine :)Indigence
You have given the same explanation for both encapsulation and abstraction !Dutch
K
22

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**
Kirshbaum answered 13/4, 2009 at 11:16 Comment(1)
Your example of encapsulation is in fact an example for abstraction.Shrunk
P
15

Difference Between Abstraction and Encapsulation.

Difference between Abstraction and Encapsulation

Plumbo answered 30/8, 2014 at 0:7 Comment(1)
Can anyone else confirm the difference is abstraction is at design level, encapsulation is at the implementation level? If so this has really cleared things up for me!Rowles
A
14

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

Appurtenant answered 18/12, 2009 at 10:58 Comment(0)
J
10

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.

Jemappes answered 11/2, 2011 at 11:12 Comment(2)
I think "way of keeping information private" is information hiding. Encapsulation is just wrapping information, that may be private or public.Snub
Encapsulation is misunderstood with Data hiding.Lowly
S
8

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.

Shroff answered 13/4, 2009 at 10:27 Comment(0)
V
8

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.

Verada answered 3/11, 2011 at 16:33 Comment(0)
D
8

Abstraction and Encapsulation by using a single generalized example

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

We all use calculator for calculation of complex problems !

image

Dogie answered 26/8, 2013 at 10:50 Comment(4)
@NehaChoudhary, I think you mean to say Your both example tell about just encapsulation, not abstraction; cause abstraction has nothing to do with hiding rather GeneralizingAubervilliers
@Aubervilliers Now, I don't think both of them even explain encapsulation!Benzidine
@Dogie If you want to tell abstraction using calulcator you might wanna go like this: There is an abstract concept of Calculator which calculates which is generalized and can be used as a base concept to make different kinds of calculator. For example, BasicCalculator and ScientificCalculator, both implementing there own ways of calculations but in the end fulfilling the criteria of generalized Calculator.Benzidine
so far the the best answer in the sea of wrong answerTel
P
8

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);
    }
}
Petuu answered 8/6, 2015 at 9:25 Comment(0)
G
7

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

Goldfinch answered 17/10, 2011 at 15:39 Comment(0)
P
6

The more I read, more I got confused. So, simply here is what I understood:

Encapsulation:

We generally see a watch from outside and it's components are encapsulated inside it's body. We have some kind of control for different operations. This way of hiding details and exposing control (e.g. setting time) is encapsulation.

Abstraction:

So far we were talking about a watch. But we didn't specify what kind of watch. It could be digital or analog, for hand or wall. There are many possibilities. What we do know is, it is a watch and it tells time and that is the only thing we are interested in, the time. This way of hiding details and exposing generic feature or use case is abstraction.

Peppers answered 18/10, 2021 at 18:51 Comment(0)
M
5

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.

Morality answered 18/11, 2014 at 19:45 Comment(0)
T
5

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

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

Triceps answered 13/7, 2015 at 5:13 Comment(0)
Z
4

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.

Zooplankton answered 1/6, 2011 at 6:39 Comment(1)
"using abstraction require more skills than encapsulation"? Citation needed.Clothe
M
4

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.

Modest answered 1/2, 2014 at 19:20 Comment(0)
T
4

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.

Terina answered 10/12, 2016 at 10:48 Comment(0)
M
3

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.

Murmurous answered 26/8, 2013 at 16:58 Comment(0)
V
2
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**
Vinita answered 6/4, 2011 at 10:57 Comment(0)
P
2

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.

Pavyer answered 8/12, 2013 at 6:15 Comment(0)
J
2

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

Judaism answered 20/4, 2017 at 16:3 Comment(0)
T
1

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.

Than answered 6/7, 2011 at 11:55 Comment(0)
H
1

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

Abstraction and Encapsulation

Hermon answered 23/6, 2013 at 2:50 Comment(0)
H
1

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

Hermon answered 7/6, 2015 at 7:26 Comment(1)
How does encapsulation uses data hiding? Acc. to tony marston encapsulation is just wrapping up of entities while nothing being mentioned about the hiding behavior. If encapsulation was "the same thing as information hiding," then one might make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).Winterkill
C
1

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.
Cline answered 18/4, 2017 at 7:21 Comment(0)
C
1

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();
        }
    }
Cline answered 23/4, 2017 at 10:11 Comment(2)
Even if IEnumerable<int> numbers was public then also here interface IOperation represents the abstraction for its implementing class. Abstraction is declaring the APIs of the class or a module or a system to the public. 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 implemwnting such a contrat 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.Judaism
yes, I believe by making interface we are sharing idea with other's rather than sharing concrete information, that's abstraction. :)Cline
F
0

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.

Foxworth answered 4/8, 2018 at 12:20 Comment(0)
S
0

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.

Satori answered 18/10, 2018 at 20:25 Comment(0)
S
0

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();
        ...
    }
}
Subside answered 22/10, 2018 at 16:29 Comment(0)
O
0

I found this article to be the most helpful: https://www.enjoyalgorithms.com/blog/encapsulation-in-oops

It draws upon Grady Booch's classic book "Object-Oriented Analysis and Design with Applications" which is widely cited as one of the first texts to formalize abstraction and encapsulation as two of the pillars of OOP. I recommend reading chapter 2 of the book for a full understanding, but I was still feeling a little unsure of my understanding and I found the summary in the article helpful.

Here's an excerpt from the article:

To understand the difference, we need to understand the idea of abstraction. In abstraction, we focus on the outside view of an object and separate essential behavior from its implementation. To encapsulate abstraction, here’s an extract from the same book of Grady Booch: "An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer."

  • Abstraction is the process of exposing observable behavior of an object, while encapsulation is the process of hiding implementation that gives rise to that behavior.
  • Abstraction addresses problems at the interface level, while encapsulation addresses them at the implementation level.
  • Abstraction involves hiding unwanted information, while encapsulation involves protecting information from the outside by enclosing it within a single entity.
  • Abstraction can be implemented using abstract classes or interfaces, while encapsulation can be implemented using access modifiers like private, protected, and public.
  • Encapsulation creates explicit barriers between different abstractions and promotes clear separation of concerns.

After summing up the differences, one can say that an abstraction consists of how an object and its behaviors are presented to the user (interface) and encapsulation is a methodology that helps the programmer create this interface!

Oppugnant answered 29/11, 2023 at 5:18 Comment(0)
H
-1

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.

Hermon answered 13/4, 2009 at 11:53 Comment(0)
P
-1

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

Pizza answered 23/4, 2015 at 10:51 Comment(1)
Why do you want to copy the same answer written below?Graphic
O
-1

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.

Overlook answered 27/11, 2015 at 9:12 Comment(0)
B
-1

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.

Basilisk answered 12/4, 2016 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.