Explain to me what is a setter and getter

前端 未结 6 1223
面向向阳花
面向向阳花 2020-12-09 18:52

What are setters and getters? Why do I need them? What is a good example of them in use in an effective way? What is the point of a setter and getter?

Update: Can I

6条回答
  •  难免孤独
    2020-12-09 19:21

    A getter is a method that gets the value of a property. A setter is a method that sets the value of a property. There is some contention about their efficacy, but the points are generally:

    • for completeness of encapsulation

    • to maintain a consistent interface in case internal details change

    More useful is when you need to add some logic around getting or setting, like validating a value before you write it.

提交回复
热议问题