Encapsulation in Object-Oriented Programming
Encapsulation is like a protective shield that prevents the data from being accessed by any code outside that shield.
Encapsulation is also known as data-hiding. We can implement encapsulation by declaring the variables in a class as private and using public methods to set and get the values of these variables.
We can also use encapsulation to hide the internal implementation of the different methods involved in an operation. An example of this is a Car
class that has private methods such as applyBrakePads()
and changePistonSpeed()
which are used by public methods such as brake()
and accelerate()
.
The benefits of encapsulation
Encapsulation minimizes a code block's dependencies to code outside of that block in order to reduce the likelihood of unexpected changes when the dependencies change. When code is hidden and self-contained, we can easily change it without breaking other parts of the application that made use of it or depended on it.
An example of encapsulation
An example of encapsulation is a section of code that is responsible for fetching data from a database or API. Encapsulation can be implemented to hide the internal details of this code and make it reusable with various types of databases or APIs.