Getters return the value of a property. They may also make a small modification of the returned result.
Let's look the following example:
Output:
Setters allow for a property to be modified. They are important since they can provide validation before a value is set.
Together getters and setters can control access and modification of a class member.
Let's look at the following example:
Output:
Explanation:
name
is
modified at line 21
without any validation.
lines 25 - 33
is defined a setter that has validation.
If the validation fails a value of 0
is set at line 28
. If validation passes
(age >= 0)
then the passed value is set (line 32
).
line 44
then
the person object's age will have a value of zero. That's due to the validation at line 26
.
_name
and _age
) are used
inside the class body.
name
and age
access / modify the _name
and _age
.line 5
_name
is replaced with name
, then
a recursion will be formed. That's the reason why properties with _
prefix are used._
prefix are meant to be accessed only inside the class body.Because private members can have validation before modification (setter) and controlled access (getter).
It seems easier to have only public members. This way there is no need for getters and setters. It's a better practice to have private members that are accessed with getter and modified through setter. This way a validation can be provided in a setter and the public access can be done only to some members - those which have getters.