- It is an Oops concept which provides the logic to hide the actual implementation of source code from user for security purpose.
- To encapsulate the data, we have to change the variable to private modifier .So that no other classes can access private data members.
- We can access the data later by using public methods which provide getter and setter implementation.
- In encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
- A class can change the implementation without affecting others program.
- A class can have total control on the data which is stored in the variable.
- A class can make variable read-only or write only.
package com.demopack1;
public class EncapsulationSample {
private String EmpName;
private int EmpNo;
private int EmpAge;
public int getAge()
{
return EmpAge;
}
public String getName()
{
return EmpName;
}
public int getNo()
{
return EmpNo;
}
public void setAge( int EmpageNew)
{
EmpAge = EmpageNew;
}
public void setName(String EmpNameNew)
{
EmpName = EmpNameNew;
}
public void setEmpNo( int EmpNoNew)
{
EmpNo = EmpNoNew;
}
public static void main(String[] args) {
EncapsulationSample encapsulationSample
= new EncapsulationSample();
//setting
values of the variables
encapsulationSample.setName("sunil");
encapsulationSample.setAge(26);
encapsulationSample.setEmpNo(105);
//Getting
values of the variables
System.out.println("Emp's name: " + encapsulationSample.getName());
System.out.println("Emp's age: " + encapsulationSample.getAge());
System.out.println("Emp's No: " + encapsulationSample.getNo());
}
}