Monday, January 9, 2017

Encapsulation in Java With examples

The whole idea behind the encapsulation is to hide the implementation details from users. It is the process of binding together the methods and data variables as a single entity.


  • If a data member is private it means it can be only accessed with in the same class
  • No outside class can access private data member(variable) of other class
  • It keeps both data and functionality safe from the outside world
  • However if we setup public getter and setter methods to update( e.g. void setLucky(int Lucky))and read (e.g. int getLucky())
  • The outside class can access those private data fields via public methods
  • That's why encapsulation also known as data hiding.




Example :

public class EncapsulationDemo{
private int Lucky;
private String empName;
private int empAge;
//Getter and Setter methods
public int getEmpLucky(){
return Lucky;
}
public String getEmpName(){
return empName;
}
public int getEmpAge(){
return empAge;
}
public void setEmpAge(int newValue){
empAge = newValue;
}
public void setEmpName(String newValue){
empName = newValue;
}
public void setEmpLucky(int newValue){
Lucky = newValue;
}
}
public class EncapsTest{
public static void main(String args[]){
EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName("sreenu");
obj.setEmpAge(32);
obj.setEmpLucky(1234);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee LUCKY: " + obj.getEmpLucky());
System.out.println("Employee Age: " + obj.getEmpAge());


}

Output:





In above example all three data members are private which can not be  accessed  directly.

so these fields can access via public methods only.field empName, Lucky, empAge are made hidden data fields using encapsulation technique of oops

Advantages of Encapsulation:

1) It improves maintainability and flexibility and re-usability
2) The field can be read only( if you don't define setter methods in the class) or write only(if you do not define getter methods in class)

3) User would not be know what is happening behind the scene.

No comments:

Post a Comment