Implement setter & getter method - Java

Q. Write a program to show the employee details using setter and getter methods.

Answer:

Encapsulation:
Encapsulation is the mechanism to bind together code(methods) and data (variable) in single unit. It is achieved by declaring class variables as private.

In this example, we implement setter and getter methods, that makes the field of class variable read only or write only.

EmpSetGet.java

public class EmpSetGet
{
   private int empId;
   private String name;
   private int age;
   private String dept;

   public int getEmpId()
   {
      return empId;
   }
   public String getName()
   {
      return name;
   }
   public int getAge()
   {
      return age;
   }
   public String getDept()
   {
       return dept;
   }
   public void setEmpId( int empId)
   {
      this.empId = empId;
   }
   public void setName(String name)
   {
      this.name = name;
   }
   public void setAge( int age)
   {
      this.age = age;
   }
   public void setDept(String dept)
   {
       this.dept = dept;
   }
}


Employee.java

public class Employee
{
    public static void main(String args[])
    {
      EmpSetGet emp = new EmpSetGet();
      emp.setEmpId(101);
      emp.setName("ABC");
      emp.setAge(25);
      emp.setDept("Testing");
      System.out.println("Employee Id : "+emp.getEmpId() + "\nName : " + emp.getName() + "\nAge : " + emp.getAge() + "\nDepartment : "+emp.getDept());
   }
}


Output:

setter getter method