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:
line 8
a getter is defined and a default value is
set for the class member side.line 20
the code won't compile. That's because
a setter is not defined.
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:
lines 7 and 8
members are defined
with getter and setter.
line 22 and 23
the setters are used.
Via customization a getter may return a modification of the member and a setter may hold validation.
Output:
Explanation:
line 7 and 8
.side
that access / modify _side
.line 12
)._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.Because members can have validation before modification (setter) and controlled access (getter).