Getters And Setters

Getters

Getters give public access to private data. They may also make a small modification of the returned result.

The syntax for defining getter is:

Let's look the following example:

Output:

Explanation:

  • At line 8 a getter is defined and a default value is set for the class member side.
  • If we uncomment line 20 the code won't compile. That's because a setter is not defined.

Setters

Setters allow for a private variable to be modified. They are important since they can provide validation before a value is set.

The syntax for defining setter is:

Let's look at the following example:

Output:

Explanation:

  • At lines 7 and 8 members are defined with getter and setter.
  • At line 22 and 23 the setters are used.

Customizing getters and setters

Via customization a getter may return a modification of the member and a setter may hold validation.

Output:

Explanation:

  • There are 2 members defined at line 7 and 8.
  • There are getters and setters for side that access / modify _side.
  • The getter returns the value rounded to two digits after decimal point (line 12).
  • At the setter the value is validated. If validation fails the new value is not set (remains the default one - 0).
  • The additional member _side is needed for both getter and setter. If line 24 is replaced with this.side = value; then an infinite recursion will be formed for the setter function.

Why using getters and setters?

Because members can have validation before modification (setter) and controlled access (getter).