Encapsulation

  • The basic idea of encapsulation is to ensure that implementation detail are not visible to users.
  • The variable of one class will be hidden from the other classes , accessible only through the method of current class.This is called data hiding.
  • To achieve encapsulation in Java, declare the class variable as private & provide public getter and setter method to modify & view the variable.Example –
class BankAccount{
      private double balance = 0;
      public void deposit(double x){
          if( x > 0 ){
              balance += x;
         }
     }
}
  • This implementation hides the balance variable , enabling access to it only through the deposit method , which validates the amount to be deposited before modifying the variable.
  • Encapsulaction provides:-
  • ┬áControl of the way data is accepted or modified.
  • more flexible & easily changed code.
  • Ability to change one part of the code without affecting other part.

Getter and Setter