Encapsulation

In an object-oriented programming language encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:

•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 operating on that data.

Programming language researchers and academics generally use the first meaning alone or in combination with the second as a distinguishing feature of object oriented programming. 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

As information hiding mechanism

Under this definition, encapsulation means that the internal representation of an object is generally hidden from view outside of the object's definition. Typically, only the object's own methods can directly inspect or manipulate its fields. This rule is strictly enforced in some languages like Smalltalk, but most other (e.g. C++ or Java) offer the programmer a degree of control over what is hidden, typically via keywords like public and private. A few languages that support object-oriented features, like Python, do not provide a mechanism to hide fields.

Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state. A benefit of encapsulation is that it reduces system complexity and thus increases robustness, by limiting the interdependencies between software components.

This mechanism is not unique to object-oriented programming. Implementations of abstract data types, e.g. modules offer a similar form of encapsulation. This similarity stems from the fact that both notions rely on the same mathematical fundament of an existential type.