[我只是想知道,使用setter方法setLocationCells
和仅声明值为[2,3,4}的int数组locationCells
有什么区别?
这里是使用setter方法的代码(第一类是主类:
public static void main(String[] args) {
SimpleDotCom dot = new SimpleDotCom();
int[] locations = {2,3,4}; // these are the location cells we will pass in
dot.setLocationCells(locations); // locationCells now 2,3,4
String userGuess = "2";
String result = dot.checkYourself(userGuess);
}
第二类:
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs) {
locationCells = locs;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for (int cell : locationCells) {
if (guess == cell) {
result = "hit";
numOfHits++;
break;
}
}
if(numOfHits == locationCells.length) {
result = "kill";
}
System.out.println(result);
return result;
}
现在,没有设置方法:
public static void main(String[] args) {
SimpleDotCom dot = new SimpleDotCom();
String userGuess = "2";
String result = dot.checkYourself(userGuess);
}
第二类:
int[] locationCells = {2,3,4};
int numOfHits;
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for (int cell : locationCells) {
if (guess == cell) {
result = "hit";
numOfHits++;
break;
}
}
if(numOfHits == locationCells.length) {
result = "kill";
}
System.out.println(result);
return result;
}
非常感谢您的帮助,非常感谢!
由于可以通过多种方式分配对象成员,因此使用getter和setter只会有助于简化Class内部和与其一起使用的内部之间的协定。这是通过公开一个接口并通常将Class成员声明为private来完成的。
如果以后更改这些成员的分配方式,提供数据验证和转换,则不必担心更改分配给它们的每个其他位置,只需更新setter或getter的内部实现即可。您的示例看似微不足道,正确无误,但随着项目的发展,setter和getter有助于降低复杂性。使用接口时,它提供了更安全的约定,因为您不仅可以处理数据类型,还可以处理各种细微的条件,例如,值为0或成员引用为null时的状态。
这里的设计原理称为封装。