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

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

    The main idea behind encapsulation is data hiding. There are several reasons why we use encapsulation in object oriented programming. Some of the identified reasons for why we encapsulation are as follows (The real use of encapsulation).

    1. Better maintainability: When all the properties are private and encapsulated, it is easy for us to maintain the program simply by changing the methods.

    2. Make Debugging Easy: This is in line with the above point. We know that the object can only be manipulated through methods. So, this makes it easy to debug and catch bugs.

    3. Have a Controlled Environment: Let the users use the given objects, in a controlled manner, through objects.

    4. Hide Complexities: Hiding the complexities irrelevant to the users. Sometimes, some properties and methods are only for internal use and the user doesn't have to know about these. This makes is simple for the user to use the object.

    So, to answer the question, "What is the use of encapsulation when I'm able to change the property values with setter methods?", given above are some of the main reasons why we use encapsulation. To provide an understanding on why, getters and setters are useful, given below are some important points, obtained from this article.

    • You can limit the values that can be stored in a field (i.e. gender must be F or M).

    • You can take actions when the field is modified (trigger event, validate, etc).

    • You can provide thread safety by synchronizing the method.

    • You can switch to a new data representation (i.e. calculated fields, different data type)

提交回复
热议问题