Questions tagged «getters»

4
重命名方法可以保留封装吗?
我正在阅读此页面,了解何时需要使用getter / setter,并且OP提供了以下代码示例: class Fridge { int cheese; void set_cheese(int _cheese) { cheese = _cheese; } int get_cheese() { return cheese; } } void go_shopping(Fridge fridge) { fridge.set_cheese(fridge.get_cheese() + 5); } 该接受的答案状态: 顺便说一句,在你的榜样,我会给类Fridge的 putCheese()和takeCheese()方法,而不是get_cheese() 和set_cheese()。这样您将仍然具有封装。 如何封装从对get / set重命名它来保存putCheese()/ takeCheese()你显然获取/设置一个值,那么为什么不干脆把它作为对get / set? 在相同的答案中,它还指出: 拥有getter和setter方法本身并不会破坏封装。破坏封装的方法是自动为每个数据成员(Java术语中的每个字段)添加一个getter和setter,而无需考虑任何问题。 在这种情况下,我们只有一个变量,cheese并且您可能想将奶酪拿回冰箱,所以在这种情况下,一对get / set是合理的。
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.