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
方法并保持 set
私有或不提供完全set
.
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屋!