在java中设置和获取方法? [英] Set and Get Methods in java?
问题描述
我如何使用set和get方法,为什么要使用它们?他们真的很有帮助吗?你也可以给我一些set和get方法的例子吗?
How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods?
推荐答案
Set和Get方法是一种数据封装模式。您可以定义 get
方法来访问这些变量,而不是直接访问类成员变量,并使用 set
方法来修改它们。通过以这种方式封装它们,您可以控制公共接口,如果您将来需要更改类的内部工作方式。
Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get
methods to access these variables, and set
methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.
例如,对于成员变量:
Integer x;
您可能有方法:
Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }
chiccodoro 还提到了一个重点。如果您只想允许对任何外来类的字段进行读取访问,则只需提供公共 get
方法并保持设置即可
私人或不提供设置
。
chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get
method and keeping the set
private or not providing a set
at all.
这篇关于在java中设置和获取方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!