Encapsulation
Encapsulation
To encapsulate something is to enclose something, in our case, we encapsulate or wrap data into a single unit essentially binding the data and code together.
i. Get and set methods:
We use set method to set value of variable and get method to get the value of variable.
Example:
Here we have get method that takes values of variables and set method that assigns arguments as values to these variables.
Here, we make object of class Example6. Let’s run this file.
Output:
Advantages of Encapsulating data:
- We can hide our data more efficiently. Hence, after implementation, user will not have any idea about the inner working of the class. To the user, only setting and initializing values is visible.
- It makes our data reusable.
- Encapsulated data is easy to test.
Disadvantages of Encapsulating data:
- Size of the code increases exponentially.
- As the size of the code increases, we need to provide additional implementation for each method.
- We provide additional methods, this increases code execution.