Definition of Encapsulation in Computer Programming

Encapsulation Protects Data

Smiling businesswomen discussing project

Thomas Barwick/Getty Images

Encapsulation in programming is the process of combining elements to create a new entity for the purpose of hiding or protecting information. In object-oriented programming, encapsulation is an attribute of object design. It means that all of the object's data is contained and hidden in the object and access to it is restricted to members of that class.

Encapsulation in Programming Languages

Programming languages aren't quite so strict and allow differing levels of access to an object's data. C++ supports encapsulation and data hiding with user-defined types called classes. A class combines data and function into a single unit. The method of hiding details of a class is called abstraction. Classes can contain private, protected and public members. Although all the items in a class are private by default, programmers can change the access levels when needed. Three levels of access are available in both C++ and C# and an additional two in C# only. They are:

  • Public: All objects can access the data.
  • Protected: Access is limited to members of the same class or descendants.
  • Private: Access is limited to members of the same class.
  • Internal: Access is limited to the current assembly. (C# only)
  • Protected Internal: Access is limited to the current assembly or types derived from the containing class. (C# only)

Advantages of Encapsulation

The main advantage of using encapsulation is the security of the data. Benefits of encapsulation include:

  • Encapsulation protects an object from unwanted access by clients.
  • Encapsulation allows access to a level without revealing the complex details below that level.
  • It reduces human errors.
  • Simplifies the maintenance of the application
  • Makes the application easier to understand.

For the best encapsulation, object data should almost always be restricted to private or protected. If you choose to set the access level to public, make sure you understand the ramifications of the choice.

 

Format
mla apa chicago
Your Citation
Bolton, David. "Definition of Encapsulation in Computer Programming." ThoughtCo, Feb. 16, 2021, thoughtco.com/definition-of-encapsulation-958068. Bolton, David. (2021, February 16). Definition of Encapsulation in Computer Programming. Retrieved from https://www.thoughtco.com/definition-of-encapsulation-958068 Bolton, David. "Definition of Encapsulation in Computer Programming." ThoughtCo. https://www.thoughtco.com/definition-of-encapsulation-958068 (accessed April 20, 2024).