What is the use of encapsulation when I'm able to change the property values with setter methods?

PSR picture PSR · May 7, 2013 · Viewed 32.2k times · Source

I try to understand a lot of times but I failed to understand this.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class.

How can we change the values of fields through setter methods? How do we prevent accessing the fields directly? What is the real use of encapsulation?

Answer

npinti picture npinti · May 7, 2013

Assume you have an age property.

The user can enter a value of -10, which although is a valid number, is an invalid age. A setter method could have logic which would allow you to catch such things.

Another scenario, would be to have the age field, but hide it. You could also have a Date of Birth field, and in it's setter you would have something like so:

...
private int age
private Date dob

...
public void setDateOfBirth(Date dob)
{
    this.dob = dob;
    age = ... //some logic to calculate the age from the Date of Birth.
}