Thursday, March 11, 2010

Object Oriented Programming: Encapsulation



What is Encapsulation (or information hiding)?

Encapsulation (as in enclosed in a capsule), sometimes called information hiding, is the ability to hide the internals of an object from its users and to provide an interface to only those members that you want the client to be able to directly manipulate. 

Encapsulation provides the boundary between a class's external interface, its public members visible to the class's users and its internal implementation details. The result is that each object exposes to any class a certain interface (those members accessible to that class). The interface must encapsulate the implementation - hide it from other parts of a program and protect an implementation from unintended actions and inadvertent access, exposing only the members of a class that will remain static, or unchanged, while hiding the more dynamic and volatile class internals. 

The advantage of encapsulation means once the interface to the object is designed you don't have to be concerned as others work on it, fix bugs and find better ways to implement it. You'll get the benefit of these improvements but none of them will affect what you do in your program. Because you're depending solely on the interface nothing they do can break your code. Your program is insulated from the object's implementation. The implementation is insulated from anything that you or other users of the object might do.

No comments: