Java Language Getters and Setters Using a setter or getter to implement a constraint


Setters and Getters allow for an object to contain private variables which can be accessed and changed with restrictions. For example,

public class Person {

    private String name;

    public String getName() {
        return name;

    public void setName(String name) {
        if(name!=null && name.length()>2)
  = name;

In this Person class, there is a single variable: name. This variable can be accessed using the getName() method and changed using the setName(String) method, however, setting a name requires the new name to have a length greater than 2 characters and to not be null. Using a setter method rather than making the variable name public allows others to set the value of name with certain restrictions. The same can be applied to the getter method:

public String getName(){
      return "Name is too large!";
      return name;

In the modified getName() method above, the name is returned only if its length is less than or equal to 16. Otherwise, "Name is too large" is returned. This allows the programmer to create variables that are reachable and modifiable however they wish, preventing client classes from editing the variables unwantedly.