What are setters and getters in Java?

Setter updates the field of an object with new value. Getter retrieves the current value of this field.

This is how they, generally, look:

public class Person {

  // field
  private String name;

  // field
  private boolean happy;

  // getter
  public String getName() {
    return name;
  }

  // setter
  public void setName(String name) {
    this.name = name;
  }

  // getter
  public boolean isHappy() {
    return happy;
  }

  // setter
  public void setHappy(boolean happy) {
    this.happy = happy;
  }
}

They are just a pair of methods, that get and set the value of a field. Nothing more.

  • Getters are named as: get + capitalized field.
  • For boolean fields, getters are named as: is + capitalized field.
  • Setters are named as: set + capitalized field.

This pattern allows you to better control the access to this field.

Person person = new Person();

person.setName("Helen");

// Helen
System.out.println(person.getName());