Encapsulation in Java

Encapsulation in Java

Encapsulation is a method of wrapping data and methods together as a single unit. In encapsulation, the variables of a class are hidden from other classes and can be accessed only through the methods of their current class. This concept is known as data hiding.

Steps to achieve encapsulation

  • Declare variables of a class as private

  • Provide public setter and getter methods to modify and view the variable values.

class Employee
{
    private int empid;
    public void setEmpid(int eid)
    {
        empid=eid;
    }
    public int getEmpid()
    {
        return empid;
    }
}
class Company
{
    public static void main(String[] args)
    {
        Employee e= new Employee();
        e.setEmpid(101);
        System.out.println(e.getEmpid());
    }
}