Encapsulation

Encapsulation

Encapsulation 

The process of binding data and corresponding methods into a single unit is nothing but encapsulation.

E.g.-:

class Student{
   data members
        +
    methods
}

If any component follows data hiding and abstraction, such type of component is said to be an encapsulated component.

Encapsulation = data hiding  + abstraction

eg-:

public class Account{
private double balance;

public double getBalance(){
    //validation
    return balance;
}
public void setBalance(double amount){
    //validation
   this.balance=amount;
}
}

The main advantage of encapsulation are -:
  • We can achieve security.
  • Enhancement will become easy
  • it improves maintainability of the application.
The main disadvantage of encapsulation are -:
The main disadvantage of encapsulation is it increases the length of the code and slows down execution.

                                                              

    Tightly Encapsulated Class


A class may be tightly encapsulated, if and only if each and every variable declared as private. Whether class contain carsponding getter and setter method are not, whether these methods are declared as public are not these things that we are not required to check.

E.g.-:

public class Account{
private double amount;
public double getAmount(){
    return amount;
}
}


Ques-: Which of the following class are tightly encapsulated?

A. class A{
          private int x;
      }
B.  class B extends A{
            int y;
      }
C.  class C extends A
         private int d;
      }
D.  class D extends B{
        private int z;
      }

Ans-: A,C.


Note-: If the parent class is not tightly encapsulated, then no child class is tightly encapsulated.
E.g.-:

class A{
         int x;
      }
 class B extends A{
           private int y;
      }
class C extends B
         private int d;
      }