79

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

4

14 回答 14

94

Encapsulation: hiding data using getters and setters etc.

Abstraction: hiding implementation using abstract classes and interfaces etc.

于 2013-06-05T11:27:00.790 回答
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.

于 2013-06-05T13:20:15.037 回答
53

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.

于 2015-12-03T16:24:21.587 回答
27

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

于 2014-11-18T19:32:27.683 回答
14
于 2015-12-03T15:58:06.493 回答
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.

于 2013-06-05T11:51:39.243 回答
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).

于 2013-06-05T12:08:42.000 回答
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.

于 2013-06-05T12:05:22.037 回答
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.

于 2016-03-23T13:05:11.953 回答
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.

于 2017-04-18T07:50:14.893 回答
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.

于 2013-06-05T11:51:06.400 回答
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.

于 2015-02-02T15:38:43.857 回答
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
于 2018-02-22T12:23:05.170 回答
0

Encapsulation

Encapsulation, in OOP, is the process of grouping together related data and behaviors in a single cohesive, functional, and self contained class unit, and “hiding” sensitive data from users with the help of private access modifiers.

Code Example in C#:

The code snippet below illustrates Encapsulation with a class modeling an ATM Machine. Notice that it contains only relevant attributes and methods and that sensitive attributes like cashLevel is hidden from outside access with private access modifiers:

public class ATMMachine
    {
        private string customerName;
        private string accountNumber;
        private decimal totalCashInAtm;

        public void WithdrawMoney()
        {
            //dispense cash to the customer and print the balance on the recepit
        }

        public void DepositMoney()
        {
            //obtain the deposit from the customer and add it to the account
        }
    }

Abstraction

Abstraction, in OOP, on the other hand, is the process of minimally exposing only what’s relevant to the user in using an object and “hiding” the irrelevant and complex mechanisms that make this useful work possible. This is achieved by using the public and private access modifiers, respectively.

Code Example in C#:

Consider a car as an analogy. For example, you don’t need to know how the electrical and mechanical systems function under the hood. You simply start the engine with the key in the ignition and drive.

  public class Car
    {
        //Data relevant to drivers
        public int speed;
        public int rpm;
        public int engineTemp;
        
        //Data for the internal system
        private int batteryVoltage;
        private int fuelInjectionRate;

        //Public user interface
        public void StartEngine()
        {
            //driver turned the key

            ActivateStarter();
        }

        //Making the car move forward
        public void Accelerate()
        {
            //driver pressed the gas pedal

            TurnPistons();
        }

        //Starting the engine
        private void ActivateStarter()
        {
            //use the batteryVoltage value and other engine data to activate the starter
        }

        //Operation of engine
        private void TurnPistons()
        {
            //use the fuelInjectionRate and other information to activate the pistons
        }
    }

On a side note, the meaning of “hiding” used in Abstraction has a subtle distinction to that used in Encapsulation. In Encapsulation, private access modifiers are used to “hide” or restrict access to sensitive data. But, in Abstraction, “hiding” refers to the use of private access modifiers to restrict user access to irrelevant attributes and methods that the user does not need to know.

For a complete explanation of Abstraction vs. Encapsulation in C#, follow this link to my Medium article.

于 2021-10-18T06:31:24.417 回答