在类中为自己的字段使用getter / setter有什么好处吗?

编程入门 行业动态 更新时间:2024-10-27 13:23:07
本文介绍了在类中为自己的字段使用getter / setter有什么好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

通常,在我自己的项目中,我使用getter和setter进行任何字段访问,然后我按照我的工作做同样的事情。前段时间,我们项目的技术主管问我为什么这样做,为什么这比仅使用字段本身更好(如果需要通过子类访问,可以选择声明它们受保护)。我无法得出一个明确的答案。

Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.

那么,是否有任何理由在类中使用getters和setter来获得类的自己的字段,或者它是否更好直接使用字段?

So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?

推荐答案

最明显的答案是副作用:

The most obvious answer is side effects:

int getCost() { if (cost == null) { calculateCost(); } return cost; }

如果您需要费用,请使用 getCost() 。如果您想查看是否已计算成本,请使用费用。

If you need the cost, use getCost(). If you want to see if cost has been calculated, use cost.

更多推荐

在类中为自己的字段使用getter / setter有什么好处吗?

本文发布于:2023-05-27 09:56:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/285734.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file 'D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!