Encapsulation

Shubham Dadasaheb Sawant
2 min readDec 29, 2021

--

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

  1. Declare instance variables/fields as private. so it cant be accessed outside the class.
  2. Provide public setter and getter methods in class to modify values of variable.

Realtime example of Encapsulation:

  1. Class containing private variables. so that this variables cannot be accessed outside the class.
  2. School bag contains books, pens that are binded together and form single unit

Advantages of Encapsulation:

  1. Security: As fields/variables are declared private they cannot be accessed outside the class
  2. 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
  3. 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.
  4. Encapsulated code is more flexible and easy to update

Disadvantage of Encapsulation :

  1. Increase in length of code
  2. 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:

  1. which class is tightly encapsulated ?
class A 
{
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 ?

class P 
{
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.

NOTE:

  1. 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.

--

--

Shubham Dadasaheb Sawant
Shubham Dadasaheb Sawant

No responses yet