81

I am preparing for an interview and decided to brush up my OOP concepts. There are hundreds of articles available, but it seems each describes them differently. Some says

Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use" (Richard Gabriel).

and is achieved through abstract classes.

Some other says

Abstraction means to show only the necessary details to the client of the object

and

Let’s say you have a method "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member,

I googled again and again and none of the results seem to give me a proper answer. Now, where does encapsulation fit in all these? I searched and found a stack overflow question. Even the answers to that questions were confusing Here, it says

Encapsulation is a strategy used as part of abstraction. Encapsulation refers to the state of objects - objects encapsulate their state and hide it from the outside; outside users of the class interact with it through its methods, but cannot access the classes state directly. So the class abstracts away the implementation details related to its state.

And here another reputed member says,

They are different concepts.

Abstraction is the process of refining away all the unneeded/unimportant attributes of an object and keep only the characteristics best suitable for your domain.

Now I m messed up with the whole concept. I know about abstract class, inheritance, access specifiers and all. I just want to know how should I answer when I am asked about abstraction and/or encapsulation in an interview.

Please don't mark it as a duplicate. I know there are several similar questions. But I want to avoid the confusion among the conflicting explanations. Can anyone suggest a credible link? A link to stackoverflow question is also welcome unless it creates confusion again. :)

EDIT: I need answers, a bit c# oriented

Community
  • 1
  • 1
Aparan
  • 1,263
  • 3
  • 12
  • 17
  • Also what about abstraction in the sense that a `Printer` class is an abstraction of a physical printer? – Matthew Watson Jun 05 '13 at 11:30
  • 2
    The problem is that there are no precise definitions for these concepts, and the words themselves have multiple meanings even within the context of object orientation. If you talk about that in an interview, I would hope that would be sufficient! – Matthew Watson Jun 05 '13 at 12:34
  • 2
    @MatthewWatson: `If you talk about that in an interview, I would hope that would be sufficient! ` I didn't get you. – Aparan Jun 05 '13 at 12:36
  • @Aparan he's saying that if you demonstrate the knowledge that both concepts are ambiguous during the interview (and give any of the below examples to show why), that alone will prove that you understand that aspect of OOP. – jszigeti Jun 05 '13 at 12:38
  • http://stackoverflow.com/questions/15176356/difference-between-encapsulation-and-abstraction/17223036#17223036 – TT_ stands with Russia Jul 12 '13 at 00:11
  • Another useful thread i found on same topic is http://stackoverflow.com/questions/761194/interface-vs-abstract-class-general-oo – Hemant Kothiyal Nov 26 '13 at 14:16
  • 1
    I hope [this article](http://www.completecsharptutorial.com/basic/understanding-concepts) would give a somewhat clear idea about the difference of the two... :) – Curiosity May 25 '17 at 01:48
  • It seems that some of the wrong answers are getting marked as correct.. I agree with Egi, Abstraction is more of generalization of properties, methods. And this is definitely not same as Abstract class . They are one of the tools for abstraction along with Interfaces, inheritance. – Andy Jul 07 '19 at 07:25

15 Answers15

96

Encapsulation: hiding data using getters and setters etc.

Abstraction: hiding implementation using abstract classes and interfaces etc.

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Taj
  • 1,718
  • 1
  • 12
  • 16
  • 6
    The number of up-votes this wrong answer has gotten is simply amazing. Though abstract classes do not have implementation, their purpose is not **Abstraction**. Their purpose is **Inheritance**, which is a totally different principle of Object Oriented Analysis and Design. – displayName Oct 10 '16 at 12:37
  • 2
    Do you mean to say that we cannot achieve abstraction without abstract class or interface? This is definitely very wrong answer. – Vikram May 17 '17 at 07:33
  • 1
    **Every function is an encapsulation** check [this](https://stackoverflow.com/a/743698/2218697) also check [this](https://stackoverflow.com/questions/16014290/simple-way-to-understand-encapsulation-and-abstraction) of **mobile phone example**. – Shaiju T Apr 20 '18 at 09:44
  • The concept of abstraction in OOP is not the same concept as stated here. For a clear comparison of Abstraction and Encapsulation in OOP, visit my blog post @ https://rajndev.medium.com/abstraction-vs-encapsulation-in-c-clearly-explained-3c1c15b7cfb6 – Raj Narayanan Oct 18 '21 at 06:13
55

Abstraction & Encapsulation Example Image source

Abstraction: is shown in the top left and the top right images of the cat. The surgeon and the old lady designed (or visualized) the animal differently. In the same way, you would put different features in the Cat class, depending upon the need of the application. Every cat has a liver, bladder, heart, and lung, but if you need your cat to 'purr' only, you will abstract your application's cat to the design on top-left rather than the top-right.

Encapsulation: is demonstrated by the cat standing on the table. That's what everyone outside the cat should see the cat as. They need not worry whether the actual implementation of the cat is the top-left one or the top-right one, or even a combination of both.


Another detailed answer here.

displayName
  • 13,888
  • 8
  • 60
  • 75
54

Abstraction means to show only the necessary details to the client of the object

Actually that is encapsulation. also see the first part of the wikipedia article in order to not be confused by encapsulation and data hiding. http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)

keep in mind that by simply hiding all you class members 1:1 behind properties is not encapsulation at all. encapsulation is all about protecting invariants and hiding of implementation details.

here a good article about that. http://blog.ploeh.dk/2012/11/27/Encapsulationofproperties/ also take a look at the articles linked in that article.

classes, properties and access modifiers are tools to provide encapsulation in c#.

you do encapsulation in order to reduce complexity.

Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use" (Richard Gabriel).

Yes, that is a good definition for abstraction.

They are different concepts. Abstraction is the process of refining away all the unneeded/unimportant attributes of an object and keep only the characteristics best suitable for your domain.

Yes, they are different concepts. keep in mind that abstraction is actually the opposite of making an object suitable for YOUR domain ONLY. it is in order to make the object suitable for the domain in general!

if you have a actual problem and provide a specific solution, you can use abstraction to formalize a more generic solution that can also solve more problems that have the same common pattern. that way you can increase the re-usability for your components or use components made by other programmers that are made for the same domain, or even for different domains.

good examples are classes provided by the .net framework, for example list or collection. these are very abstract classes that you can use almost everywhere and in a lot of domains. Imagine if .net only implemented a EmployeeList class and a CompanyList that could only hold a list of employees and companies with specific properties. such classes would be useless in a lot of cases. and what a pain would it be if you had to re-implement the whole functionality for a CarList for example. So the "List" is ABSTRACTED away from Employee, Company and Car. The List by itself is an abstract concept that can be implemented by its own class.

Interfaces, abstract classes or inheritance and polymorphism are tools to provide abstraction in c#.

you do abstraction in order to provide reusability.

Egi
  • 1,256
  • 9
  • 20
  • 2
    http://stackoverflow.com/a/8960961/2401223 It says `Encapsulation is a strategy used as part of abstraction` – Aparan Jun 06 '13 at 04:24
  • I see .. there are different meanings behind abstraction. Wikipedia also differs between "Abstraction" and the "Abstraction principle". Stick to what Matthew Watson told you in the comments "The problem is that there are no precise definitions for these concepts, and the words themselves have multiple meanings even within the context of object orientation." As long as you can give them one ore more meanings in an interview everything will be fine :) – Egi Jun 06 '13 at 08:05
  • Thank you. I m gonna follow that advice :) – Aparan Jun 06 '13 at 11:43
  • "List by itself is an abstract concept" - I think it is deviating from the programming concept of abstraction since List class is a concrete class if not an interface. – user30478 Oct 31 '18 at 06:04
  • I don't think so. Interfaces are not abstractions, but can be. Concrete classes are not abstractions but can be. http://blog.ploeh.dk/2010/12/02/Interfacesarenotabstractions/ Also there is an IList interface in .net. you could be right thought, i guess i am conflating abstractions in a domain and abstractions in code. – Egi Oct 31 '18 at 09:11
28

I will try to demonstrate Encapsulation and Abstraction 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 complete 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.

UPDATE: There is an video on this link to explain the sample: What is the difference between Abstraction and Encapsulation

fbarikzehy
  • 4,885
  • 2
  • 33
  • 39
Sanchit
  • 1,145
  • 11
  • 6
14

Below is a semester long course distilled in a few paragraphs.

Object-Oriented Analysis and Design (OOAD) is actually based on not just two but four principles. They are:

  • Abstraction: means that you only incorporate those features of an entity which are required in your application. So, if every bank account has an opening date but your application doesn't need to know an account's opening date, then you simply don't add the OpeningDate field in your Object-Oriented Design (of the BankAccount class). Abstraction in OOAD has nothing to do with abstract classes in OOP.

    Per the principle of Abstraction, your entities are an abstraction of what they are in the real world. This way, you design an abstraction of Bank Account down to only that level of detail that is needed by your application.

  • Inheritance: is more of a coding-trick than an actual principle. It saves you from re-writing those functionalities that you have written somewhere else. However, the thinking is that there must be a relation between the new code you are writing and the old code you are wanting to re-use. Otherwise, nobody prevents you from writing an Animal class which is inheriting from BankAccount, even if it is totally non-sensical.

    Just like you may inherit your parents' wealth, you may inherit fields and methods from your parent class. So, taking everything that parent class has and then adding something more if need be, is inheritance. Don't go looking for inheritance in your Object Oriented Design. Inheritance will naturally present itself.

  • Polymorphism: is a consequence of inheritance. Inheriting a method from the parent is useful, but being able to modify a method if the situation demands, is polymorphism. You may implement a method in the subclass with exactly the same signature as in parent class so that when called, the method from child class is executed. This is the principle of Polymorphism.

  • Encapsulation: implies bundling the related functionality together and giving access to only the needful. Encapsulation is the basis of meaningful class designing in Object Oriented Design, by:

    • putting related data and methods together; and,
    • exposing only the pieces of data and methods relevant for functioning with external entities.

Another simplified answer is here.


People who argue that "Abstraction of OOAD results in the abstract keyword of OOP"... Well that is incorrect.

Example: When you design a University in an application using object oriented principles, you only design an "abstraction" of the university. Even though there is usually one cash dispensing ATM in almost every university, you may not incorporate that fact if it's not needed for your application. And now though you have designed only an abstraction of the university, you are not required to put abstract in your class declaration. Your abstract design of university will be a normal class in your application.

displayName
  • 13,888
  • 8
  • 60
  • 75
10

I think they are slightly different concepts, but often they are applied together. Encapsulation is a technique for hiding implementation details from the caller, whereas abstraction is more a design philosophy involving creating objects that are analogous to familiar objects/processes, to aid understanding. Encapsulation is just one of many techniques that can be used to create an abstraction.

For example, take "windows". They are not really windows in the traditional sense, they are just graphical squares on the screen. But it's useful to think of them as windows. That's an abstraction.

If the "windows API" hides the details of how the text or graphics is physically rendered within the boundaries of a window, that's encapsulation.

Mike Panter
  • 489
  • 2
  • 11
  • Can you provide a source to back your concept? – Aparan Jun 05 '13 at 11:59
  • This Wikipedia page: [http://en.wikipedia.org/wiki/Abstraction_(computer_science)](http://en.wikipedia.org/wiki/Abstraction_(computer_science)) contains a good example in Java, with a class called "animal" which is an abstraction. The class encapsulates the fact that an animal has "EnergyReserves" - the caller doesn't need to know this. Instead, the caller simply knows whether the animal "isHungry". EnergyReserves is hidden (encapsulated). – Mike Panter Jun 07 '13 at 01:54
  • This is the answer I will vote for. But, the abstraction example is not very elucidating to me since I expected to see some abstract class or interface stuff, not the general English idea of abstraction. – user30478 Oct 31 '18 at 06:52
4

my 2c

the purpose of encapsulation is to hide implementation details from the user of your class e.g. if you internally keep a std::list of items in your class and then decide that a std::vector would be more effective you can change this without the user caring. That said, the way you interact with the either stl container is thanks to abstraction, both the list and the vector can for instance be traversed in the same way using similar methods (iterators).

AndersK
  • 35,813
  • 6
  • 60
  • 86
  • 2
    with all due respect I will stick with my explanation :) i.e. encapsuling hiding from user, abstraction more of a common concept like an interface that several classes share. – AndersK Jun 05 '13 at 12:14
  • 1
    Hm.. This is what I said in my question itself. Everyone has his own concepts on this topic :). Can you provide a credible link to back your explanation? – Aparan Jun 05 '13 at 12:16
  • http://www.codeproject.com/Questions/298285/difference-between-data-hidding-encapsulation-abst – Aparan Jun 05 '13 at 12:24
  • no i don't have a link, this is how I have understood it from various books like Code Complete. – AndersK Jun 05 '13 at 12:31
  • http://www.c-sharpcorner.com/UploadFile/tusharkantagarwal/objectorientedcsharp11162005070743AM/objectorientedcsharp.aspx plz check these two links and tell me what to accept – Aparan Jun 05 '13 at 12:31
  • http://www.c-sharpcorner.com/UploadFile/tusharkantagarwal/objectorientedcsharp11162005070743AM/objectorientedcsharp.aspx seems on the spot – AndersK Jun 05 '13 at 19:53
  • But it says `Abstraction is the ability to generalize an object as a data type that has a specific set of characteristics and is able to perform a set of actions. Object-oriented languages provide abstraction via classes`. I dont think abstraction is that simple. – Aparan Jun 06 '13 at 04:48
  • I will suggest you not to consider c-sharpcorner.com, tutorialspoint.com, javatpoint.com, beginnersbook.com. All these Indian websites are a total crap without any OO literature or reference. They straightly put content from the cheap training centers. Spreading wrong information by copy paste and made OOAD, a top ranking on google, mess on the internet. Read OracleDocs, MSDN or Wiki. P.S. I am myself an Indian. – user30478 Oct 31 '18 at 06:36
3

One example has always been brought up to me in the context of abstraction; the automatic vs. manual transmission on cars. The manual transmission hides some of the workings of changing gears, but you still have to clutch and shift as a driver. Automatic transmission encapsulates all the details of changing gears, i.e. hides it from you, and it is therefore a higher abstraction of the process of changing gears.

Lorentz Vedeler
  • 5,101
  • 2
  • 29
  • 40
  • "Automatic transmission encapsulates all the details of changing gears, i.e. hides it from you" ... actually that is why I would say that the automatic vs. manual transmission on cars is a good example for ENCAPSULATION! and not for abstraction. automatic transmission is not an abstraction of the manual transmission, it is another concept. an abstraction would be if you say that a car needs a power transmission system ignoring how the actual interface for the driver will be (automatic or manual). – Egi Jun 05 '13 at 13:41
  • I see your point. The way I see it though, abstraction and encapsulation are related. If you don't have any encapsulation you don't have any abstraction. Through encapsulation you can find more abstract concepts, so the automatic transmission is a better abstraction than the manual transmission. Maybe you don't even need a concept for transmission, perhaps you only need the concept of a car moving forward, that would encapsulate all of the internal workings of the car. – Lorentz Vedeler Jun 05 '13 at 14:30
  • 1
    I absolutely agree with your last statement. you can abstract everything away until nobody has an idea what it is actually about anymore. but I disagree with your first statement. you can practice encapsulation without abstraction, for example by making a program with only one big class that handles everything and hides all the implementation details from the client. and abstraction without encapsulation is also possible by making a program out of classes that are small and have a single responsibility yet do not hide any implementation details or any invalid state. – Egi Jun 05 '13 at 15:10
1

Encapsulation: Hiding implementation details (NOTE: data AND/OR methods) such that only what is sensibly readable/writable/usable by externals is accessible to them, everything else is "untouchable" directly.

Abstraction: This sometimes refers specifically to a type that cannot be instantiated and which provides a template for other types that can be, usually via subclassing. More generally "abstraction" refers to making/having something that is less detailed, less specific, less granular.

There is some similarity, overlap between the concepts but the best way to remember it is like this: Encapsulation is more about hiding the details, whereas abstraction is more about generalizing the details.

Bradley Thomas
  • 4,060
  • 6
  • 33
  • 55
1

Abstraction and Encapsulation are confusing terms and dependent on each other. Let's take it by an example:

public class Person
    {
        private int Id { get; set; }
        private string Name { get; set; }
        private string CustomName()
        {
            return "Name:- " + Name + " and Id is:- " + Id;
        }
    }

When you created Person class, you did encapsulation by writing properties and functions together(Id, Name, CustomName). You perform abstraction when you expose this class to client as

Person p = new Person();
p.CustomName();

Your client doesn't know anything about Id and Name in this function. Now if, your client wants to know the last name as well without disturbing the function call. You do encapsulation by adding one more property into Person class like this.

public class Person
        {
            private int Id { get; set; }
            private string Name { get; set; }
            private string LastName {get; set;}
            public string CustomName()
            {
                return "Name:- " + Name + " and Id is:- " + Id + "last name:- " + LastName;
            }
        }

Look, even after addding an extra property in class, your client doesn't know what you did to your code. This is where you did abstraction.

CredibleAshok
  • 73
  • 1
  • 9
0

As I knowit, encapsulation is hiding data of classes in themselves, and only making it accessible via setters / getters, if they must be accessed from the outer world.

Abstraction is the class design for itself.

Means, how You create Your class tree, which methods are general ones, which are inherited, which can be overridden,which attributes are only on private level, or on protected, how Do You build up Your class inheritance tree, Do You use final classes, abtract classes, interface-implementation.

Abstraction is more placed the oo-design phase, while encapsulation also enrolls into developmnent-phase.

icbytes
  • 1,831
  • 1
  • 17
  • 27
0

I think of it this way, encapsulation is hiding the way something gets done. This can be one or many actions.

Abstraction is related to "why" I am encapsulating it the first place.

I am basically telling the client "You don't need to know much about how I process the payment and calculate shipping, etc. I just want you to tell me you want to 'Checkout' and I will take care of the details for you."

This way I have encapsulated the details by generalizing (abstracting) into the Checkout request.

I really think that abstracting and encapsulation go together.

FrankO
  • 2,522
  • 6
  • 24
  • 34
0

Abstraction

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

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

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

Encapsulation:

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

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

Let's go back 6 million years,

Humans are not fully evolved. To begin with, evolution created a hole next to each body part to inject nutrients, which you can decide on yourself.

However, as humans get older, the nutrient requirements for each body part change Humans don't know which body parts need how much of which nutrient.

Evolution realised that exposing the hole next to each body part was a mistake, so it corrected it by encapsulating the entire body in skin and exposing only one opening, later it was called as "mouth." 

Also, it abstracted the whole implementation of nutrient allocation through digestive system. All you have to do is keep eating through your mouth. The digestive system will take care of the body's nutrient composition changes to meet your needs. 

In the software world, requirements will keep changing.

Encapsulating the internal data and exposing only the required functions will help with better maintenance. As a result, you have greater control over what occurs within your class/module/framework. 

Abstraction makes it easier for the client to consume a class/module/framework. So clients don't have to do(know) 100 different steps to get the desired output. Exposed function/class will do all the work. In our example, you don't have to worry about which nutrients are required for which body part. Just eat it. 

Mona
  • 342
  • 1
  • 3
  • 17
0

You use Abstraction when you defined classes for each of the different account types. Those classes described the behavior for that type of account.

You use Encapsulation when you kept many details private in each class.

You use Inheritance when you leveraged the implementation already created in the BankAccount class to save code.

You use Polymorphism when you created virtual methods that derived classes could override to create specific behavior for that account type.

Fadi
  • 585
  • 4
  • 22