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

前端 未结 15 2082
情深已故
情深已故 2020-12-08 11:08

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 provi

15条回答
  •  孤街浪徒
    2020-12-08 11:22

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

提交回复
热议问题