Getters And Setters


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

Let's look the following example:



  • If we uncomment line 14 the code will not compile. That's because a private member (declared at line 5) cannot be directly accessed outside the class body.
  • At line 15 a private member is accessed outside the class body. That's not done directly (like in line 14) 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:


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:



  • Value of the private member name is modified at line 20 without any validation.
  • At lines 24 - 32 is defined a setter that has validation. If the validation fails a value of 0 is set at line 27. If validation passes (age >= 0) then the passed value is set (line 31).
  • If we uncomment line 52, then the person object's age will have a value of zero. That's due to the validation at line 26.

Why using getters and setters?

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.