Jump to content

Information hiding

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by RoseParks (talk | contribs) at 10:12, 2 September 2002. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In object-oriented programming theory, encapsulation (also called "information hiding") is the practice of hiding the data structures that represent the internal state of an object from access by anything other than the publicly-exposed methods of that object. This ensures that objects cannot change the internal state of other objects in unexpected ways, minimizing the complexity of putting together modules of code from different sources.

The two main advantages of encapsulation are:

  1. The data structure that represents the state can be reimplemented without affecting the implementation of the other objects. For example if the state of a point is represented internally with Cartesian coordinates then this might be changed to Polar coordinates without changing the interface of the object, i.e, without changing which messages with which arguments are understood by the object and what the type of the result of these messages will be.
  2. The state of the object can be guarded by the methods. The data structure that represents the state of the object may allow certain values that are not considered meaningful, e.g., a percentage may be represented by an integer that allows numbers larger than 100. The methods that update this integer can then ensure that it never rises above 100.

Many languages allow the programmer to bypass encapsulation, or to specify varying degrees of encapsulation for specific object types. In Java, for example, a class might be defined like this:

 class Cow extends Mammal {
   public Tail m_tail;
   private Horns m_horns;
   
   public void eat(Food f) {
     super.eat(f);
     chewcud();
   }
   private void chewcud() {
     . . .
   }
 }

With the Cow type as defined above, some piece of code external to Cow's implementation would be allowed to access m_tail directly, without going through any of the methods that Cow has chosen to expose as its interface. Such code would not, however, be able to access m_horns. Likewise, the method eat() is exposed as part of the Cow's interface, so any other object would be able to cause the cow object to eat by calling that method, passing it the offered food item as an argument to the method. External code would not be able to directly cause the cow to call its chewcud() method (nor would it even know such a method existed; only the cow itself knows or cares that eating involves chewing its cud).

More to be said about how various languages handle encapsulation.

See also: