Getter and Setter in java

Let’s learn getter and setter in java.

Getter and Setter in java

Get and set methods are basically used in Encapsulation. Encapsulation means hiding sensitive date from user. To hide sensitive data from user we have to declare class variables as private.

We all know private variables in a class can only be accessed within same class and cannot be accessed outside the class. To access private variables of a class provide public get and set methods.

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

For example:

public class Student
{
   private String name;
   // getter method
   public String getName()
   {
      return name;
   }
   // setter 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.

Here 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 access private variable we get error like this,

Exception in thread “main” java.lang.Error: Unresolved compilation problems:
The field Student.name is not visible
The field Student.name is not visible

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

Dhoni

Rather, use getName() method and setName() method to access and change variable.

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