Encapsulation
Encapsulation is the process of wrapping the data and code under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
Contents
Why do we need Encapsulation
Encapsulation provides a way to protect data(Data-Hiding), Increases Flexibility, Re-usability and Testability.
- Data-Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is stored values in the variables. He only knows that we are passing the values to accessors and variables are getting initialized to that value.
- Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to only use Get Accessor in the code. If we wish to make the variables as write-only then we have to only use Set Accessor.
- Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
- Testing code is easy(Testability): Encapsulated code is easy to test for unit testing.
Implementation of Encapsulation
Encapsulation is implemented by using access specifiers, which defines the scope and visibility of a class member:
- Public
- Private
- Protected
- Internal
- Protected internal
Public
Public access specifier allows all the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.