问题:
What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables? 使用仅获取和设置的getter和setter而不是仅对这些变量使用公共字段的优点是什么?
If getters and setters are ever doing more than just the simple get/set, I can figure this one out very quickly, but I'm not 100% clear on how: 如果getter和setter所做的不只是简单的get / set,我可以很快地弄清楚这一点,但是我不清楚如何做到这一点:
public String foo;
is any worse than: 比以下任何方面都更糟糕:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Whereas the former takes a lot less boilerplate code. 而前者需要更少的样板代码。
解决方案:
参考一: https://stackoom.com/question/6Zvn/为什么要使用getter和setter-accessor参考二: https://oldbug.net/q/6Zvn/Why-use-getters-and-setters-accessors
来源:oschina
链接:https://my.oschina.net/stackoom/blog/4303668