Jump to content

Information hiding

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Conversion script (talk | contribs) at 15:51, 25 February 2002 (Automated conversion). 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 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.

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.