Getter and Setter Definition and Usage
Getter:
Definition:
A Getter is a method used to retrieve the value of a specific field. Typically, the name of a Getter method follows the format getFieldName().
Usage:
// In this example, a Getter method for the "color" field is defined in the Car class. This method returns the value of the "color" field.
public class Car {
private String color;
public String getColor() {
return color;
}
}
Setter:
Definition:
A Setter is a method used to set the value of a specific field. Typically, the name of a Setter method follows the format setFieldName(argument).
Usage:
// In this example, a Setter method for the "color" field is defined in the Car class. This method sets the value of the "color" field to the value received as an argument.
public class Car {
private String color;
public void setColor(String color) {
this.color = color;
}
}
Benefits of Getter and Setter:
Using Getter and Setter methods allows you to access class fields through methods rather than directly accessing the fields. This provides control over the field’s values, ensuring data integrity and security.
Additionally, using Getter and Setter methods makes it easier to modify the field’s implementation later, if needed.