33

What are the differences between information hiding and encapsulation?

I have read that encapsulation means bundling data and the procedures that should operate on them together. If that is so, does the following class achieve encapsulation?

class IsThisEncapsulation {
    public int age;

    public int getAge() {
        return this.age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Now would declaring the data attribute age private achieve information hiding?

Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
user1720616
  • 543
  • 1
  • 6
  • 13
  • 2
    *"is the class IsThisEncapsulation an example of Encapsulation?"* => you have not really encapsulated anything since you provide getters and setters that can read and write the state of your class directly... – assylias Dec 17 '12 at 11:24
  • 1
    @assylias Making `age` public is what breaks encapsulation, not providing getter and setter... – hyde Dec 17 '12 at 11:30
  • @hyde I had not noticed that "detail"! Indeed! – assylias Dec 17 '12 at 11:31
  • @hyde i read that encapsulation means bundling data and methods together if that is so the class that i have made(IsThisEncapsulation) does achieve encapsulation.Am i correct?Or have i read about encapsulation incorrectly. – user1720616 Dec 17 '12 at 12:01
  • 2
    @user1720616 For encapsulation to be meaningful, you need some invariants (conditions which must remain true). For age you could define invariant: age can't be negative. So, if it's possible to set negative age (instead of getting exception or whatever), as it obviously is if age is public field, then age is not encapsulated properly. Another might be, if you have many fields which depend on each other, so you can't just modify one field, you need code which does proper modifications to all fields that need it. – hyde Dec 17 '12 at 12:29

9 Answers9

37

Encapsulation and information hiding are very closely linked concepts, though their precise definitions vary depending on who you talk to.

The concept of "information hiding" was first described by Parnas (1972) who suggested that access to information should be restricted to reduce the interconnectedness of a system. He proposed that this would facilitate splitting of a system into modules while maintaining a user-friendly external interface and allowing implementation details to be changed without affecting clients.

The term "encapsulation" was coined by Zilles (1973) to describe the use of procedures to control access to underlying data in order to reduce system complexity and protect data from dangerous modification.

Subsequently, Parnas (1978) described information hiding and encapsulation (and abstraction) as synonymous terms, which describe the hiding of details of a system that are likely to change. However, distinctions have been drawn between information hiding and encapsulation, such as by Micallef (1987), who described encapsulation as "the strict enforcement of information hiding". Some authors, such as Cohen (1984) and Abreu and Melo (1996) describe "encapsulation mechanisms", especially in object-oriented programming languages, as allowing information hiding.

Meyers (2000) suggests that the degree to which a piece of code is encapsulated depends on the amount of code which would be broken if it changed. In this sense, private data and methods are more encapsulated the fewer methods by which they can be accessed. In contrast, public data and methods are completely unencapsulated, as the amount of code by which they can be accessed is unknown.

Conversely, Rogers (2001) suggests that encapsulation is simply the language mechanism that allows data to be bundled with methods that operate on that data. He claims that encapsulation fundamentally has nothing to do with information hiding. However, this definition is counter to almost all usage of the term in the academic literature in the 28 years prior to the publication of his article. There are a few other examples of this usage, for example Archer and Stinson (1995), but they are few and far between and not particularly notable.

In conclusion, information hiding is the idea that information should be hidden so that a design can be changed without affecting clients. This allows for increased flexibility and safety. Encapsulation may be considered to be the same as information hiding, but the term is often used to describe the practical implementation of information hiding, especially in object-oriented programming.

As an example of information hiding/encapsulation, consider this class:

public class BankAccount {
    public int dollars;
}

The implementation of this class is completely unencapsulated, which means it is inflexible (e.g. we cannot easily add support for individual cents in the future) and unsafe (e.g. the account can changed to be negative). However, if we hide the data behind a formally defined interface of methods, we gain flexibility and safety.

public class BankAccount {
    private int dollars;

    public void deposit(int dollars) {
        this.dollars += Math.max(0, dollars);
    }
}

We now have control over how the state is modified, and we can also change the implementation without breaking client code:

public class BankAccount {
    private int cents;

    public void deposit(int dollars) {
        deposit(dollars, 0);
    }

    public void deposit(int dollars, int cents) {
        this.cents += Math.max(0, 100 * dollars) + Math.max(0, cents);
    }
}

The class is now better encapsulated because we have hidden information about its underlying implementation.

Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
Joseph Thomson
  • 9,888
  • 1
  • 34
  • 38
  • 5
    This one is backed much better than the accepted answer. +1 – Piovezan Oct 12 '19 at 21:41
  • 2
    This answer is a useful survey of the ideas along with an excellent set of references. Readers will find chasing down and reading the original material to be quite rewarding. That said, I'm going to pick at the references. :-) The reference "Micallef (1987)" is actually a link to Alan Snyder, "Inheritance and the development of encapsulated software systems", a chapter in the book Shriver/Wegner, _Research directions in object-oriented programming_, MIT Press, 1987. – Stuart Marks Apr 25 '23 at 21:57
  • 2
    I think the reference "Micallef (1987)" was intended to refer to Micallef, _Encapsulation, Reusability and Extensibility in Object-Oriented Programming Languages_, Columbia University Computer Science Technical Report CUCS-285-87, 1987. https://academiccommons.columbia.edu/doi/10.7916/D8TT4ZZD (PDF available). It looks like the quote is from Micallef so that report was probably the intended link. However, the Snyder reference seems relevant as well. – Stuart Marks Apr 25 '23 at 22:00
23

Well I know that making fields private and then making setter and getter of the fields is encapsulation. However, does encapsulation mean just this?

---> Encapsulation is an OOP concept where object state(class fields) and it's behaviour(methods) is wrapped together. Java provides encapsulation using class.

Information Hiding:

--> mechanism for restricting access to some of the object's components. Your above example is the case of Information Hiding if you make age private.


Initially, Information/Data Hiding was considered the part of Encapsulation, and the definitions of Encapsulation would be as:

  • A language mechanism for restricting access to some of the object's components.
  • A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

the second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus, information hiding is defined as a separate notion by those who prefer the second definition.

Reference: wikipage

bora.oren
  • 3,439
  • 3
  • 33
  • 31
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
5

There is subtle difference between those, I like description from "Growing Object-Oriented Software Guided by Tests" book written by Steve Freeman and Nat Pryce:

Which says:

Encapsulation

Ensures that the behavior of an object can only be affected through its API. It lets us control how much a change to one object will impact other parts of the system by ensuring that there are no unexpected dependencies between unrelated components.

Information hiding

Conceals how an object implements its functionality behind the abstraction of its API. It lets us work with higher abstractions by ignoring lower-level details that are unrelated to the task at hand.

Eds
  • 781
  • 1
  • 5
  • 7
1

This is an old question but I came across a very helpful example to share with everyone.

You are correct that encapsulation is bundling of data with the methods that operate on that data. You are also correct that setting age to private means information hiding.

While the word "encapsulating" seems to imply "hiding", it does not "hide information" here.

The example from Encapsulation is not information hiding helps demonstrate (the difference between) encapsulation and information hiding.

The following are a Position class and a utility class PositionUtility that acts on it.

public class Position {
    public double lat;
    public double lon;
}
public class PositionUtility {
    // the distance between the two Positions
    public static double distance(Position pos1, Position pos2)  { /* an implementation */ }

    // the angle of Position pos1 towards Position pos2
    public static double heading(Position pos1, Position pos2) { /* an implementation */ }
}

A typical use case for this code would be

Position myHouse = new Position();
myHouse.lat = 30.0;
myHouse.lon = 50.0;

Position coffeeShop = new Position();
coffeeShop.lat = 31.0;
coffeeShop.lon = 49.0;

double distance = PositionUtility.distance(myHouse, coffeeShop);
double heading = PositionUtility.heading(myHouse, coffeeShop);

The code has no encapsulation and information hiding. In order to adhere to encapsulation, you should let Position itself handle the operations involving lat and lon.

public class Position {
    public double lat;
    public double lon;

    // the distance between this Position and another Position pos
    public double distance(Position pos) { /* an implementation */ }

    // the angle of this Position towards another Position pos
    public static double heading(Position pos) { /* an implementation */ }
}

Now you have encapsulation. Whenever you need to call distance and heading you do not need an external class (namely PositionUtility) to access the fields in Position.

However, other classes can still access and modify its public fields lat, lon. If you want to enforce certain constraints on these fields, those fields would need to be private and modifying and retrieving them have to be done through getters/setters.

public class Position {
    private double lat;
    private double lon;
    
    public Position(double lat, double lon) {
        setLatitude(lat);
        setLongitude(lon);
    }
    
    public void setLatitude(double lat) {
        // some checking
        this.lat = lat;
    }
    
    public void setLongitude(double lon) {
        // some checking
        this.lon = lon;
    }
    
    public double getLatitude() { return lat; }
    public double getLongitude() { return lon; }
    // ...
}

Now you achieve information hiding. The actual data structure used by Position is no longer visible to other classes. Now, you could change your underlying implementation without affecting the users.

As an example, you can use phi and theta as your private fields and use radian instead of degree for calculation. A user using getLatitude() and other getters/setters would not be aware that your internal data structure no longer contains lat and lon (and that should not matter to them anyway).

public class Position {
    private double phi;
    private double theta;
    
    public Position(double lat, double lon) {
        setLatitude(lat);
        setLongitude(lon);
    }

    public void setLatitude(double lat) { setPhi(Math.toRadian(lat)); }
    public void setLongitude(double lon) { setTheta(Math.toRadian(lon)); }
    
    private void setPhi(double phi) {
        // some checking
        this.phi = phi;
    }
    
    private void setTheta(double theta) {
        // some checking
        this.theta = theta;
    }
    
    public double getLatitude() { return Math.toDegrees(phi); }
    public double getLongitude() { return Math.toDegrees(theta); }
    // ...
}

If information hiding hadn't been in place, this change in implementation would not be possible without affecting other classes, as they could be directly accessing the public lon and lat fields already.

James Koh
  • 11
  • 1
  • 2
0

just see their literal meaning. Encapsulation is just putting things in a bag. i.e. putting all the attributes and methods in a class achieves Encapsulation However to a certain extent you also achieve information hiding by encapsulation. access modifiers don't contribute in encapsulation but in information hiding.

Harit Vishwakarma
  • 2,338
  • 4
  • 21
  • 36
  • Thank you so much.So if access modifies dont contribute to encapsulation the class that i have defined here does achieve encapsulation doesnot it? – user1720616 Dec 17 '12 at 12:03
  • @Harit I'd say encapsulation also means, invariants of the encapsulated object must remain true. This requires accessing the object only through public API. Whether the language prevents accessing them bypassing the API or not (enforces information hiding or not) is another matter, but encapuslation is not just lumping things together, it also includes the invariants. – hyde Dec 17 '12 at 12:35
0

To Answer your question:

Information hiding: Is hiding the essential parts of the object which expose the way it is implemented internally and exposing higher abstractions. For e.g. : In a TV remote, we are exposed to only the keys to interact with the TV, we are not aware of what goes inside.

Encapsulation: Encapsulation is combining data and methods and allowing the internal data to be accessed by public methods. So, yes, if in your class, you make the variable age, private, you will achieve encapsulation

stamhaney
  • 1,246
  • 9
  • 18
  • Umm i have read that encapsulation means bundling data and methods together and also someone here has posted that access modifiers dont contribute to encapsulation .If these statements are true then the class that i have defined does achieve encapsulation.Am i wrong?Please do correct me if i am.And i meant that if i made the field private would it achieve information-hiding. – user1720616 Dec 17 '12 at 12:05
  • Encapsulation is putting a security around the data you do want to protect from unauthorised access. This can be achieved with access specifiers and public functions. The variable age is declared as public in your class, so it can be accessed from outside and can be changed, which is not what we want. So we need to make it private. Information hiding can be achieved with abstraction, which is exposing behavior which does not show how you are saving/using the internal data. So, in this example, if you make it private, you would achieve information hiding. – stamhaney Dec 17 '12 at 12:22
0
class NoEncapsulationNoInformationHiding { 
    public List widths = new ArrayList();
}

class EncapsulationNoInformationHiding {
    private ArrayList widths = new ArrayList();

    public ArrayList getWidths() {
        return this.widths;
    }
}

class EncapsulationInformationHiding {
    private List widths = new ArrayList();

    public List getWidths() {
        return this.widths;
    }
}
  • Encapsulation: combining things, such as data and the procedures that operate on these data (making up an object). Encapsulation implies the hiding of an object’s data because any procedures can operate on public data.
  • Information hiding: abstracting things, such as an object’s implementation i.e. an object’s data, the implementation of its procedures, and the classes of the parameters and return values of its procedures. Information hiding implies encapsulation, but not the other way round.

Examples inspired from William Underwood’s.

Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
Alireza Rahmani Khalili
  • 2,727
  • 2
  • 32
  • 33
0

This is what happens when you do not implement information hiding, encapsulation or whatever it called. Bad things occur when you change something in somewhere in a corner that you think that is independent. Secondly when you want to change a third-party library that is used in your system, that you find out there are references everywhere in the system that you cannot move without refactoring the whole thing. For example, you want to upgrade your data access library version (I faced this issue when I wanted to update ODP.net version), you estimate the work is thinking that you want to modify the DataAccess class that supposed to have reference to the DB client library. But you find out that every business class has created a reference for the DB client library. Now you have to update references of 60 assemblies instead of one :( Information leaking

The same thing happens when you expose internal logic to clients. For example, you have a function EnrollMember(string flag) you accept "A," "B" as valid flags and do some logic inside the function. When you want to change this function later, you cannot do it without informing the clients.

-1

-> Encapsulation allows us to provide access to certain parts of an object, restricting, at the same time, access to others. In other words, encapsulation allows us to do information hiding.

-> Information hiding is actually the process or act of restricting

thox
  • 129
  • 4
  • 13