Sunday 7 January 2018

4.9 Encapsulation

Encapsulation : Binding of data members and member function into a single unit is called encapsulation.

Java suggests that, Your variables in your classes should be private so that no one can access it or modify it. It should only modify using methods.

getter and setter is a method to perform encapsulation.


class Emp
{
private int empId;
private String empName;

public void setEmpId(int empId)
{
this.empId=empId;
}
public int getEmpId()
{
return empId;
}

public void setEmpName(String empName)
{
this.empName=empName;
}
public String getEmpName()
{
return empName;
}
}
class encapsulation
{
public static void main(String args[])
{   Emp obj1=new Emp();
obj1.setEmpId(1);
obj1.setEmpName("Bikes");

Emp obj2=new Emp();
obj2.setEmpId(2);
obj2.setEmpName("Amitesh");

System.out.println("Emp Id = "+obj1.getEmpId()+" & Name = " + obj1.getEmpName());
System.out.println("Emp Id = "+obj2.getEmpId()+" & Name = " + obj2.getEmpName());
}
}

No comments:

Post a Comment