Java Getter Setter

Summary: in this tutorial, you will learn how to use the Java Getter and Setter methods to control access to private fields.

Introduction to Java Getter Setter methods

In the previous tutorial, you learned how to use the private access modifier to mark a field as private and prevent direct access to it from the outside of the class.

To provide access to the private field, you need to define a pair of public methods and use these public methods to access the private field.

In Java, these public methods are called getter and setter methods.

Defining Getter methods

A getter method retrieves the value of a private field. Typically, it follows the naming convention getFieldName for the field named fieldName:

class MyClass {
    private int fieldName;

    public int getFieldName() {
        return fieldName;
    }
}Code language: Java (java)

Defining Setter methods

A setter method modifies the value of the private field. When defining a setter method, you follow the naming convention setFieldName for a field named fieldName:

public class MyClass {
    private int fieldName;

    public void setFieldName(int value) {
        fieldName = value;
    }
}Code language: Java (java)

Typically, a private field has both getter and setter methods. But if a private field only has the getter method, it is called a readonly field.

Java Getter/Setter example

The following example shows how to define the getter/setter methods for the name and age fields:

class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}Code language: Java (java)

The getter/setter method seems to be redundant. Instead of defining getter/setter methods for each field, why not make them all public?

The reason is that the getter and setter methods will bring many benefits. For example, you can perform validation within the setter methods to ensure that only valid values are set.

The following shows how to perform a validation that checks the name and age in the setter methods before assign them to the corresponding fields:

class Person {
    private String name;
    private int age;

    public void setName(String name) {
        if (!name.isEmpty()) {
            this.name = name;
        }
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }
}Code language: Java (java)

In this example, we assign a value to the name field if it is not empty and a value to the age field if it is greater than zero.

The following illustrates how to use the getter and setter methods of the Person class:

public class App {
    public static void main(String[] args) {

        var person = new Person();

        person.setName("John");
        person.setAge(22);

        System.out.printf("It's %s. I am %d.",
                person.getName(),
                person.getAge()
        );

    }
}Code language: Java (java)

Output:

It's John. I am 22

Benefits of Using Java Getter and Setter Methods

Here are the benefits of using Java getter and setter methods:

  • Encapsulation: Getter and setter methods help you encapsulate the internal state of an object by wrapping the private field and providing controlled access and modification.
  • Validation: Setter methods can perform validation and error checking to ensure the integrity of the state of the object.
  • Flexibility: Getter and setters provide a consistent API so that you change their internal implementations, they do not affect the external API of the class.
  • Readability: Getter and setter methods make your code easier to read and self-explanatory.

Summary

  • Use Java Getter/Setter methods to encapsulate private fields.
  • Use Getter methods to get the values of private fields.
  • Use Setter methods to set the values to private fields.
Was this tutorial helpful ?