getter and setter in java

Let’s learn getter and setter in java.

getter and setter in java

get method returns the value of variable and set method sets the value.

For example:

public class Student
{
   private String name;
   // get method
   public String getName()
   {
      return name;
   }
   // set method
   public void setName(String stuName)
   {
      this.name = stuName;
   }
}


In the above example get method returns value of variable ‘name’.

While set method takes parameter ‘stuName’ and assigned to ‘name’ variable.

NOTE: this keyword refers to current object.

Since String variable ‘name’ is declared as private it cannot be accessed from outside the class ‘Student’.

public class GetSetDemo
{
   public static void main(String[] args)
   {
      Student obj = new Student();
      obj.name = "Dhoni";
      System.out.println(obj.name); // error - private access modifier
   }
}


In the above example if we declare String variable ‘name’ as public output will be

Dhoni

Rather use getName() and setName() methods to access and change variables.

public class GetSetDemo
{
   public static void main(String[] args)
   {
      Student obj = new Student();
      obj.setName("Dhoni");
      System.out.println(obj.getName());
   }
}