The Pragmatic Craftsman :: Simplicity from complexity : by Stanley Kubasek ::

Encapsulation vs Abstraction

I must admit. I am still having hard time seeing a real difference. I am still having hard time defining them both.One thing I am sure: both are fundamental principles of object oriented programming. I am going to try to learn them here and explain the differences. Just so I know for future.

“Abstraction and encapsulation are not synomous,” says P.J. Plauger in Programming on Purpose.

Encapsulation is information hiding. I think that’s the best way to define it and remember it. “Information hiding allows for implementation of a feature to change without affecting other parts that are depending on it.”

P.J. Plauger has a great analogy and definition of information hiding.”Information hiding is not the same as secrecy. The idea is not to prevent outsiders from knowing what you are doing inside a module. Rather, it is to encourage them not to depend on that knowledge. That leads to a kind of secondary coupling which is more pernicious than obvios dependency because it is less visible. You should encapsulate information to keep it private, not secret. (What you do in the bathroom is no secret, but it is private.)”

“Stuff all of the code that is likely to change in a module [class] and hide its innards.” That not only defines information hiding, but it is also a fundamental principle developing: when to create a new class, when to refactor.

Abstraction. Look at it as “what” the method or a module does not “how” it does it. I just found a great definition of abstraction: “The notion abstraction is to distill a complicated system down to its most fundamental parts and describe these parts in a simple, precise language.”

Let’s compare Java and C++. We have a good example of abstraction. In C++, you have to deal with pointers and references a lot. You have to deal a lot of garbage collection. In essence, you have to work on a low level. (C and C++ in turn abstracted a lot of even lower level machine code.) In Java, those things are abstracted away. You just assume they exist. In essence, abstraction means that you are working on a higher level. You don’t care how pointers work in Java, you just assume that they work. You don’t have to concentrate on the lower level stuff, you work on higher level.

I think abstraction is extremely important. By working more abstractly we can solve more and more difficult problems because we don’t have to concentrate on the lower level details. As Steve McConnel puts it, we are working closer to the business domain.

So to summarize, I think I got it now. Encapsulation is information hiding. Abstraction means working on a higher level, not worrying about the internal details. They go hand in hand. The bottom line, even if you still don’t know the differences, utilize information hiding; make your programs more abstract by creating classes with responsibility and then talk about the feature by the name of the class, but what it does, not by how it is doing it (that’s abstraction, I think).

11 Responses to “Encapsulation vs Abstraction”

  1. I see that several people are searching for “abstraction” and “encapsulation.”
    Here are some additional good definitions:http://homepages.ius.edu/gmanwani/C202/abstraction_means_concentrating_.htm

  2. manyam says:

    Now I am dam clear about the difference… Excellent article.

  3. Chauhan says:

    “Encapsulation is information hiding. Abstraction means working on a higher level, not worrying about the internal details.” Encapsulation hides data and Abstraction hides implementation then what is the main difference. I think encapsulation is a data binding as information of one object is only related to that one and if that particular object gets destroyed then al information related to that object gets destroyed. Abstraction on the other hand is data hinding technique hides all implementation.

  4. stanley says:

    Chauhan,
    Not sure what you mean. The way you explain it makes it even more confusing…
    You want to think about your system on a higher level, using class names, using real objects. That’s abstraction — not having to concentrate on low-level details. For instance, when constructing a house, you don’t concentrate on what nails will be used (low level detail, not enough abstraction), you concentrate on how many rooms, etc (high level — nicely abstracted).
    Encapsulation, in a way, is the implementation of abstraction. By encapsulating, you hide the internals of the method, or a class. Read the section of this article on encapsulation, “Information hiding allows for implementation of a feature to change without affecting other parts that are depending on it.”

  5. Gaurav Sharma says:

    I think Abstraction is hiding unwanted details, like we have a customer object which uses a very complex data access layer to fetch the Customer from DataBase. Its only programmers headache to thin and implement that layer. There is no need for end user to nkow How this Customer is fetched from DB? Which Db is he using? What’s the connection string like?….and all that complex stuff…All he knows is that, he wants to get information about XYZ Customer and he gets it by selecting his name from the Combo box and clicking ‘Show Details’ button.
    On the other hand Encapsulation means , grouping together the data and operations that we are going to perform on that data together. This means creating a class with variables, properties and functions. We provide a specific interface using which user can manipulate this data. If we provide a function GetCustomerSalary(string CustomerName)…then to get a Customer’s Salary .. user will allways have to provide Customer name as there is no other way he can do that (else provided by programmer).
    Its simple you have a car and you know how to drive it. Just use the keys and turn them to start the car. What happens inside is not the drivers job. This is abstraction.
    Once you are inside the car and you want to change the gear, you can only do that using the interface provided i.e. Gear Knob. There no other way you can do that. This is encapsulation.

  6. Syam says:

    What does it mean for a programming language to support abstraction? I thought if you are able to create a class and instantiate objects, then ur language supports abstraction. If you are able to assign private/public/protected modifiers, then ur language supports encapsulation. Now, from the discussion here, it seems like I got quite a few things wrong here.
    Cant understand why things have to be so complex? Abstraction and Encapsulation are supposedly the pillars of OOP. If there is so much scope for confusion about the pillars themselves, how can we simplify complex systems using these?

  7. Syam says:

    Or is abstraction the ability to define an abstract method, class, interface? Sorry for pulling things down to the implementation level, but I need that to understand concretely.

  8. Rohit kumar says:

    Hi Syam, this is for you…….!!
    Encapsulation and Data Abstraction
    Encapsulation facilitates data abstraction, which is the relationship between a class and its datamembers. Encapsulation refers to the fact that the data variables (also called the properties) and themethods (also called the behavior) are encapsulated together inside a template called a class. The data members encapsulated inside a class may be declared public, private, or protected. However, good object-oriented programming practice requires tight encapsulation. That means all data membersof the class should be declared private. That is, the code outside of the class in which the datamembers are declared can access them only through method calls, and not directly. This is calleddata abstraction (or data hiding), because now the data is hidden from the user, and the user canhave access to it only through the methods.Encapsulation (and data abstraction) makes the code more reliable, robust, and reusable. This isso because the data and the operations on it (methods) are encapsulated into one entity (the class),and the data member itself and the access to it are separated from each other (tight encapsulation or data abstraction). For example, in tight encapsulation, where your data members are private, if you change the name of a data variable, the access code will still work as long as you don’t change the name of the parameters of the method that is used to access it.
    Consider the code example in Listing 5-1.
    Listing 5-1. TestEncapsulateBad.java1. public class TestEncapsulateBad {2. public static void main(String[] args) {3. EncapsulateBad eb = new EncapsulateBad();4. System.out.println(“Do you have a headache? ” + eb.headache);5. }6. }7. class EncapsulateBad {8. public boolean headache = true;9. public int doses = 0;10.}The output from this code follows:Do you have a headache? TrueNote that in line 4, the data variable of class EncapsulateBad is accessed directly by the codepiece eb.headache. This is only possible because the variable headache is declared public in the class EncapsulateBad. If you declare this variable private, line 4 will cause a compiler error. Let’s say you keep it public, and then you change the name of the variable headache in the EncapsulateBad class to something else. In this case, line 4 will again generate an error, because you need to change the name of the variable headache in line 4 to the new name as well.However, a better solution is to separate the data variable from the access by declaring itprivate and provide access to it through methods, as shown in Listing 5-2.Listing 5-2. TestEncapsulateGood.java1. public class TestEncapsulateGood {2. public static void main(String[] args) {3. EncapsulateGood eg = new EncapsulateGood();4. eg.setHeadache(false);5. System.out.println(“Do you have a headache? ” + eg.getHeadache());6. }7. }8. class EncapsulateGood {9. private boolean headache = true;10. private int doses = 0;11. public void setHeadache(boolean isHeadache){12. this.headache = isHeadache;13. }14. public boolean getHeadache( ){15. return headache;16. }17. }The output from this code follows:Do you have a headache? falseNote that the variable headache is now declared private (line 9), and it can be accessed throughmethods setHeadache(…) and getHeadache(), which are declared public (lines 11 and 14). The worldcan still access your data, but this access process is separated from the details of the data—the data variable name, how the change is made to it, and so forth. This hiding of the data details from the access procedure is called data abstraction. In an application, it means you can make changes to the data variables in your class without breaking the API. Such protection also makes the code more extendible and easier to maintain. So, the benefits of encapsulation are: hard-to-break reliable code, easy maintenance, and extensibility.
    About the AuthorPAUL SANGHERA, Ph.D., SCJP, SCBCD, who contributed to developing the SCJPexam for Java 5, has been programming in Java for 10 years and has substantialexperience teaching Java. As a software engineer, Paul has contributed to thedevelopment of world-class technologies such as Netscape Communicatorand Novell’s NDS. He has been director of software development and directorof project management at successful startups such as WebOrder andMP3.com. He has taught Java and other technology courses at severalinstitutes in the San Francisco Bay Area, including San Jose State University,Golden Gate University, California State University, Hayward, and Brooks College. With a master’s degree in computer science from Cornell University and a Ph.D. in physics from Carleton University, he has authored and co-authored more than 100 technical papers published in well-reputed European and American research journals. Paul has also presented talks by invitation at several international scientific conferences. He is the best-selling author of several books on technology and project management. Paul lives in Silicon Valley, California, where he works as an independent information consultant.

  9. Hosting says:

    What is difference between encapsulation and abstraction and how are they related to each other?

  10. Chintan says:

    Excellent article…Now, i am damp sure about this concept…
    Below is my understanding. Read it thoughly…
    Abstraction comes first, Encapsulation satisfies what abstraction promise to do so.
    So, what abstraction says?
    Abstraction asked to concentrate on “What” system does and neglect on “How” system does. Let
    me put in practical example.
    I am very found of design/UML diagrams. When i start my new module, i always begin it with
    UML diagrams. Lets says, my requirement is to get some records from sql server to a web page
    do some stuffs and then save it to XML file.
    So, from UML diagram perspective, i will create one rough box (think it as a class), which fetch some data from database and put it in web page and from web pg to
    xml file.
    Very important now – here, i ask myself (drawing rough box) as “what” is my requirement?, but i did not concentrate on “how” my requirement will be fulfull(e.g. how many if condition, how many loops etc. etc.). This is abstraction.
    Now comes encapsulation: Encapsulation asked to concentrate on “how” to do what abstraction
    ask to do i.e. fetching data from database, put it in web page, save it to xml.
    Encapsulation also hide irrelevant details (i.e. informatin hiding)
    So, here, we will write
    all implementation code to do the stuffs. Methods to open database connection, query it,
    assign data to each text box in web pg, create xml nodes, save value to nodes, saving xml
    file and many methods. However, all methods are not relevant to developer to know. So, i
    will hide (information hiding) method which are not relevant and will only expose those method which will do the stuffs. I will expose methods such as OpenConnection(), SaveDataToWebPg(), SaveToXML().

  11. [...] Encapsulation vs Abstraction, a blog post I wrote a few years ago, is the most popular post on this blog. So I decided to revisit the subject. This time, I want to focus more on encapsulation. [...]

Favorite Quote

Topics

Tags

Archive

Currently Reading

Info

© 2001-2013 Stanley Kubasek About me :: Contact me

Me on Twitter

»see more

Recent Entries