Explain to me what is a setter and getter

前端 未结 6 1220
面向向阳花
面向向阳花 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:30

    One question which might pop out of this is if using a method instead of a direct field access might decrease performance. Answer is not really as compilers optimize code so that if your method is only doing return field;, where field is the field in your class that you hide with the setter/getter, it will actually access the field directly. Thus you get in most cases the same performance, at the same time keeping the option of later on change what set/get methods do.

    Effective Java Programming of Joshua Block is a great book with tips on how to write good code, and explains why as well. Why using setter/getter is one of the hints.

    Note: You might notice that in some books/documentation fields that present a setter/getter instead of being directly accessible are called 'properties' instead of fields. E.g. in C#, you can even specify that a field is a property and you don't need to define set/get anymore (nice feature I think).

提交回复
热议问题