Definition: Process of binding data and corresponding methods together into a single unit is called encapsulation
For eg :
Class itself is an example of encapsulation. Class contains variables and corresponding methods that are binded together. That means this class variables can not be accessed outside this class.
To achieve encapsulation we need to
- Declare instance variables/fields as private. so it cant be accessed outside the class.
- Provide public setter and getter methods in class to modify values of variable.
Realtime example of Encapsulation:
- Class containing private variables. so that this variables cannot be accessed outside the class.
- School bag contains books, pens that are binded together and form single unit
Advantages of Encapsulation:
- Security: As fields/variables are declared private they cannot be accessed outside the class
- Setter methods helps to set the value of variable in class. If your class doesn’t have setter method then you cant write/modify that variable that is variable can be read-only
- Getter method helps to get the value of variable in class. If your class doesn’t have getter method then you cant read that variable i.e it can be only write-mode operation only.
- Encapsulated code is more flexible and easy to update
Disadvantage of Encapsulation :
- Increase in length of code
- Slow the execution
Tightly Encapsulated Class:
If each and every variable in class is declared as private. Then that class is called as Tightly Encapsulated class. In tightly encapsulated class it is not required that getter and setter method should be private or public. checking getter n setter method access specifier is not important.
Example to understand encapsulation:
- which class is tightly encapsulated ?
private int x = 10;
class B extends A
int y = 10;
class C extends A
private int z = 10;
=> A and C as fields/variables are private.
2. which class is tightly encapsulated ?
int a = 10;
class Q extends P
private int b = 10;
class R extends Q
private int z = 20;
=> None of the above classes are tightly encapsulated as class P has public variable and this variable will be inherited into subclasses ie class Q and R . So none of above three classes are tightly encapsulated.
- If parent class is public then no need to check below subclasses as this class variables will be inherited to below classes. So none of the class will be tightly encapsulated.