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

前端 未结 15 2072
情深已故
情深已故 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:34

    By using encapsulation you separate your class from the out-side world (other classes) and out-side world can access and modify your class instance variables through access modifiers, which provides several benefits:

    -You can do some logging in your getter/setter methods.

    -You can validate /normalize (for example trim spaces, remove special character,...) Your input in setter method.

    And also you can hide your implementation from the outside world, for example you have a collection like array list in your class and you write your getter method like this

    public List get collection(){
     return new  ArrayList(this.arrayList);
    }
    

    So in this case, in the future if you decide to change your implementation of collection from array list to something else like linked list, you are free to do so because out side world doesn't know anything about your implementation.

提交回复
热议问题