Sunday, November 8, 2015

Encapsulation in Java with Example

Encapsulation : 

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.


For Example :

 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 :  
Employee Name      = sreenu
Employee LUCKY  = 1234
Employee age          = 32

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

Advantage 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 dont define getter methods in class)
3) User would not be know what is happening behind the scene.




No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...