使用 getter 和 setter(称为 encapsulation 或 data-hiding)的一些好处:
1.类的字段可以设为只读(仅提供 getter)或只写(仅提供 setter)。这使该类可以完全控制谁可以访问/修改其字段。
例子:
class EncapsulationExample {
private int readOnly = -1; // this value can only be read, not altered
private int writeOnly = 0; // this value can only be changed, not viewed
public int getReadOnly() {
return readOnly;
}
public int setWriteOnly(int w) {
writeOnly = w;
}
}
2。类的用户不需要知道类实际如何存储数据。这意味着数据是独立于用户而独立存在的,因此可以更轻松地修改和维护代码。这允许维护人员进行频繁的更改,例如错误修复、设计和性能增强,同时不会影响用户。
此外,封装的资源可供每个用户统一访问,并且具有独立于用户的相同行为,因为该行为是在类内部定义的。
示例(获取值):
class EncapsulationExample {
private int value;
public int getValue() {
return value; // return the value
}
}
现在,如果我想返回两倍的值怎么办?我可以更改我的 getter,所有使用我的示例的代码都不需要更改,并且将获得两倍的值:
class EncapsulationExample {
private int value;
public int getValue() {
return value*2; // return twice the value
}
}
3.使代码更简洁、更易读、更易于理解。
这是一个例子:
无封装:
class Box {
int widthS; // width of the side
int widthT; // width of the top
// other stuff
}
// ...
Box b = new Box();
int w1 = b.widthS; // Hm... what is widthS again?
int w2 = b.widthT; // Don't mistake the names. I should make sure I use the proper variable here!
带封装:
class Box {
private int widthS; // width of the side
private int widthT; // width of the top
public int getSideWidth() {
return widthS;
}
public int getTopWIdth() {
return widthT;
}
// other stuff
}
// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!
看看在第二个示例中,您对获取的信息有多少控制权,以及这是否更清晰。请注意,这个例子是微不足道的,在现实生活中,您将处理许多不同组件访问的大量资源的类。因此,封装资源可以更清楚地了解我们正在访问哪些资源以及以何种方式(获取或设置)。
这里是 good SO thread 关于这个主题的。
这里是good read 数据封装。