Getters give public access to private data. They may also make a small modification of the returned result.
Let's look the following example:
Output:
There are 2 things to notice in the code:
line 19
the code will not compile. That's because
a private member (declared at line 5
) cannot be directly accessed
outside the class body.line 20
a private member is accessed outside the class body.
That's not done directly (like in line 19
) but through a public function
- a getter. This is how a private member can be accessed outside the class body.
Let's add more stuff:
Output:
The only things that were added are 2 getters - getPerimeter
and
getArea
. Simply they are getters that return a private member
with a small modification.
Setters allow for a private variable to be modified. They are important since they can provide validation before a value is set.
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
.
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.