问题描述
当您可以仅公开变量并避免诸如A.setVariableX(A.getVariableY())
这样的行的麻烦时,getter和setter的用途是什么?
What is the use of getters and setters when you can just make your variables public and avoid the hassle of such lines as A.setVariableX(A.getVariableY())
?
推荐答案
隐藏实施细节.如果您选择将属性公开,然后再决定更改其工作方式,则必须更改所有关联的代码.
To hide implementation details. If you choose to make your properties public instead, then later decide to change the way they work, you have to change all of the associated code.
使用getter和setter方法,您通常可以在不更改可见API的情况下更改内部实现细节(从而避免必须更改使用所涉及类的API的任何代码).
With getters and setters, you can often change the internal implementation details without changing the visible API (and thus avoid having to change any of the code that uses the API of the class in question).
这篇关于吸气剂和吸气剂的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!