我有以下界面:
public interface Goal {
...
public boolean setParentGoal(Goal g); //should be private?? but how?
public Goal getParentGoal();
}
我觉得拥有一个私有(private)二传手在这里会更有意义吗?因为我不希望任何人能够随意“改变”目标的父级。
但是当我删除它时,我会遇到以下情况:
public boolean addSubGoal(Goal g) {
if(g==this) return false;
childGoals.add(g);
g.setParentGoal(this); //compile error, cannot resolve method
return true;
}
如何“优雅”地解决这种情况?
最佳答案
首先,如果您不知道的话,接口(interface)
中的所有方法默认都是public
,因此您不能将它们设为private
.
由于您不希望任何人更改实例的状态,因此我建议您在创建对象本身时将它们传递到构造函数
中。因此实例的状态无法更新,其他人所能做的就是根据需要创建新实例。
Point
类没有任何 setter 方法来更新 Point
对象创建后的状态。坐标值在构造函数本身中传递。
public class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
关于java - 如何解决界面中似乎需要 setter 的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34249748/