如何解决在界面中似乎需要设置器的情况?

时间:2015-12-13 09:41:24

标签: java oop interface

我有以下界面:

public interface Goal {
    ...
    public boolean setParentGoal(Goal g); //should be private?? but how?
    public Goal getParentGoal();
}

我觉得好像有一个私人二传手会更有意义吗?因为我不希望任何人能够直接“改变”目标的父母。

然而当我删除它时,我会遇到以下情况:

public boolean addSubGoal(Goal g) {
    if(g==this) return false;
    childGoals.add(g);
    g.setParentGoal(this); //compile error, cannot resolve method
    return true;
}

如何“优雅地”解决这种情况?

1 个答案:

答案 0 :(得分:1)

首先,如果您不知道,interface中的所有方法都是默认public,因此您无法将它们private

由于您不希望任何人更改您的实例的状态,我建议您在创建对象本身时在constructor中传递它们。因此,实例的状态无法更新,其他所有操作都可以,如果需要,可以创建新实例。

Point类没有任何用于在创建后更新Point对象状态的setter方法。坐标的值在构造函数本身中传递。

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;
  }
}