use*_*630 47 java methods getter setter encapsulation
我如何使用set和get方法,为什么要使用它们?他们真的很有帮助吗?你也可以给我一些set和get方法的例子吗?
Jus*_*ier 54
Set和Get方法是数据封装的模式.您可以定义get访问这些变量的set方法以及修改它们的方法,而不是直接访问类成员变量.通过以这种方式封装它们,您可以控制公共接口,如果您将来需要更改类的内部工作方式.
例如,对于成员变量:
Integer x;
Run Code Online (Sandbox Code Playgroud)
你可能有方法:
Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }
Run Code Online (Sandbox Code Playgroud)
chiccodoro也提到了一个重点.如果您只想允许对任何外来类的字段进行读取访问,则可以通过仅提供公共get方法并保持set私有或根本不提供内容来实现set.
sti*_*vlo 22
我想添加其他答案,可以使用setter来防止将对象置于无效状态.
例如,假设我要设置一个TaxId,建模为String.setter的第一个版本可以如下:
private String taxId;
public void setTaxId(String taxId) {
this.taxId = taxId;
}
Run Code Online (Sandbox Code Playgroud)
但是我们最好阻止使用无效的taxId来设置对象,所以我们可以引入一个检查:
private String taxId;
public void setTaxId(String taxId) throws IllegalArgumentException {
if (isTaxIdValid(taxId)) {
throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
}
this.taxId = taxId;
}
Run Code Online (Sandbox Code Playgroud)
下一步,为了改善程序的模块性,将TaxId本身作为一个对象,能够自我检查.
private final TaxId taxId = new TaxId()
public void setTaxId(String taxIdString) throws IllegalArgumentException {
taxId.set(taxIdString); //will throw exception if not valid
}
Run Code Online (Sandbox Code Playgroud)
同样对于吸气剂,如果我们没有价值怎么办?也许我们希望有一条不同的道路,我们可以说:
public String getTaxId() throws IllegalStateException {
return taxId.get(); //will throw exception if not set
}
Run Code Online (Sandbox Code Playgroud)
我想你想要这样的东西:
public class Person {
private int age;
//public method to get the age variable
public int getAge(){
return this.age
}
//public method to set the age variable
public void setAge(int age){
this.age = age;
}
}
Run Code Online (Sandbox Code Playgroud)
你只是在一个对象实例上调用这样的方法.这种方法特别有用,如果设置某些东西应该有副作用.例如,如果您想对某些事件作出反应,例如:
public void setAge(int age){
this.age = age;
double averageCigarettesPerYear = this.smokedCigarettes * 1.0 / age;
if(averageCigarettesPerYear >= 7300.0) {
this.eventBus.fire(new PersonSmokesTooMuchEvent(this));
}
}
Run Code Online (Sandbox Code Playgroud)
当然,如果有人忘记setAge(int)在他应该的地方打电话并age直接使用,这可能会很危险this.age.
具有访问器方法比直接访问字段更受欢迎,因为它控制字段的访问方式(可以强加数据检查等)并适合接口(接口不能要求字段存在,只有方法).
Setter和getter用于替换从外部类直接访问成员变量.如果您在访问属性时使用setter和getter,则可以包括初始化,错误检查,复杂转换等.一些示例:
private String x;
public void setX(String newX) {
if (newX == null) {
x = "";
} else {
x = newX;
}
}
public String getX() {
if (x == null) {
return "";
} else {
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
342853 次 |
| 最近记录: |