在一些领域对象的方法中,他们不直接使用属性,而是使用get方法。为什么 ?一个例子如下:
private List<String> errorCodeList = new ArrayList<String>();
/**
* Add all errors to the error list.
*/
public void addAllErrors(Collection<String> theErrorStrings) {
if (errorCodeList == null) {
errorCodeList = new ArrayList<String>();
}
for (String aString: theErrorStrings) {
getErrorCodeList().add(aString);
}
}
/**
* @return the errorCodes
*/
public List<String> getErrorCodeList() {
return errorCodeList;
}
/**
* Set the error strings.
*/
public void setErrorCodeList(List<String> allErrors) {
this.errorCodeList = allErrors;
}
最佳答案
这是封装的问题。通过仅通过 getter 和 setter 提供对实例变量的访问,您隐藏了内部表示。因此,您可以在不修改接口(interface)的情况下更改实现。您可能会决定使用 HashMap 来存储错误代码(无论出于何种原因)会更方便,一旦您更改了它,访问该字段的所有代码都会中断。但是,如果您提供了 getter 和 setter,尽管您更改了内部表示,您仍可以保持它们的原样。
此外,更容易确保不变量保持在适当位置,如果每个人都可以访问这些字段,您将无法做到这一点。
关于java - 为什么不直接使用属性而是使用 getXXX() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7847012/