Encapsulation

Get familiar with important aspects of object-oriented programming called data hiding and encapsulation.

Data hiding

Data hiding is an essential concept in object-oriented programming. In simple terms, it can be defined as masking a class's internal operations and only providing an interface through which other entities can interact with the class without being aware of what is happening within.

The goal is to implement classes in a way that prevents unauthorized access to or modification of the original contents of a class by its instances (or objects). The underlying algorithms of one class need not be known to another class. The two classes can still communicate, though.

Components of data hiding

Data hiding can be divided into two primary components:

  • Encapsulation

  • Abstraction

When used together, they allow us to make efficient classes for further use in our application.

Encapsulation

Encapsulation is a fundamental programming technique used to achieve data hiding in OOP. Encapsulation in OOP refers to binding data and the methods to manipulate that data together in a single unit—class.

Encapsulation is usually done to hide the state and representation of an object from the outside. A class can be thought of as a capsule with methods and attributes inside it.

When encapsulating classes, a good convention is to declare all variables of a class private. This will restrict direct access by the code outside that class.

At this point, a question can be raised. If the methods and variables are encapsulated in a class, how can they be used outside that class? The answer to this is simple. One has to implement public methods to let the outside world communicate with this class. These methods are called getters and setters. We can also implement other custom methods.

Implementing encapsulation in programming languages

In this section, we will show how to implement encapsulation using some of the most popular object-oriented programming languages, such as Java, C#, Python, C++, and JavaScript.

For the sake of explanation, we’ll start off by creating a simple Movie class, which contains the following three data members (attributes):

  • title

  • year

  • genre

Below is the implementation of the Movie class in different OOP languages.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.