java getters and setters

java

In Java, getter and setter methods are used to access and modify the fields (variables) of an object. Getter methods are used to retrieve the value of a field, and setter methods are used to set the value of a field.

Here is an example of how you can define getter and setter methods in Java:

public class Person {
  private String name;
  private int age;

  // getter method for the name field
  public String getName() {
    return name;
  }

  // setter method for the name field
  public void setName(String name) {
    this.name = name;
  }

  // getter method for the age field
  public int getAge() {
    return age;
  }

  // setter method for the age field
  public void setAge(int age) {
    this.age = age;
  }
}

In this example, the Person class has two fields: name and age, both of which are private. The getName() and getAge() methods are the getter methods for these fields, and the setName(String name) and setAge(int age) methods are the setter methods.

To use these methods, you can create an instance of the Person class and call the getter and setter methods on it:

Person person = new Person();

// set the name field using the setName() method
person.setName("John");

// get the name field using the getName() method
String name = person.getName();

// set the age field using the setAge() method
person.setAge(30);

// get the age field using the getAge() method
int age = person.getAge();

Getter and setter methods are commonly used in Java to encapsulate the fields of an object and provide a way to access and modify them in a controlled manner. They also allow you to define additional behavior or validation when accessing or modifying the fields, which can be useful for maintaining the integrity of the object’s state.