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 23
the code will not compile. That's because
a private member (declared at lines 10
) cannot be directly accessed
outside the class body.line 24
a private member is accessed outside the class body.
That's not done directly (like in line 23
) 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
member is
modified at line 25
without any validation.
lines 30 - 38
is defined a setter that has validation.
If the validation fails an error is thrown at line 33
. If validation passes
(age >= 0)
then the new value is set (line 37
).
line 52
an error will be thrown
when the code executes. That's due to the validation at line 32
.
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.