What is an accessor method in Java?

An accessor method in Java returns the value of a private field, and is named after this field like so: getFieldName.

For example, here getFirstName is an accessor method for field firstName:

class Person {

  private String firstName;

  public Person(String firstName) {
    this.firstName = firstName;
  }

  public String getFirstName() {
    return firstName;
  }
}

As their name implies, accessor methods give you control over how the field is accessed.

In the example above, we allow only read access to the field. Write access is given only once — in the constructor.