Java Language Adding Getters and Setters


Example

Encapsulation is a basic concept in OOP. It is about wrapping data and code as a single unit. In this case, it is a good practice to declare the variables as private and then access them through Getters and Setters to view and/or modify them.

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

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String getName() {
    return name;
  }

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

These private variables cannot be accessed directly from outside the class. Hence they are protected from unauthorized access. But if you want to view or modify them, you can use Getters and Setters.

getXxx() method will return the current value of the variable xxx, while you can set the value of the variable xxx using setXxx().

The naming convention of the methods are (in example variable is called variableName):

  • All non boolean variables

     getVariableName()   //Getter, The variable name should start with uppercase
     setVariableName(..) //Setter, The variable name should start with uppercase
    
  • boolean variables

      isVariableName()     //Getter, The variable name should start with uppercase
      setVariableName(...) //Setter, The variable name should start with uppercase
    

Public Getters and Setters are part of the Property definition of a Java Bean.