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

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.
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)