Hi Guys, after long break…Today we will discuss one of the most important concept ‘Encapsulation‘ It’s quite difficult to understand the concept of encapsulation from a definition. So let’s understand what encapsulation is by looking at some code examples.Basically, there are two forms of encapsulation in OOP.
First, encapsulation is a technique that packages related data and behaviors into a single unit.
Let’s see an example:
Advantages of encapsulation:
- It improves maintainability and flexibility and re-usability: for e.g. In the above code the implementation code of
void setEmpName(String name)and
String getEmpName()can be changed at any point of time. Since the implementation is purely hidden for outside classes they would still be accessing the private field empName using the same methods (
getEmpName()). Hence the code can be maintained at any point of time without breaking the classes that uses the code. This improves the re-usability of the underlying class.
- The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we don’t define the getter methods in the class). For e.g. If we have a field(or variable) which doesn’t need to change at any cost then we simply define the variable as private and instead of set and get both we just need to define the get method for that variable. Since the set method is not present there is no way an outside class can modify the value of that field.
- User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call
set methodand to read a field call
get methodbut what these set and get methods are doing is purely hidden from them.
Encapsulation is also known as “data Hiding”.
- Objects encapsulate data and implementation details. To the outside world, an object is a black box that exhibits a certain behavior.
- The behavior of this object is what which is useful for the external world or other objects.
- An object exposes its behavior by means of public methods or functions.
- The set of functions an object exposes to other objects or external world acts as the interface of the object.