代码重复继承

code duplication inheritence

public abstract class Agent1 {
    public abstract void actOn(Object o);
    public void repeat(Object o, int i) {
       for (int j = 1; j <= i; j++) {
            actOn(o);
        }
    }
}

public abstract class Agent2 {
    public abstract void actOn(Object o, int i);
    public void repeat(Object o, int i) {
        for (int j = 1; j <= i; j++) {
            actOn(o, j);
        }
    }
}

如何通过减少代码重复来改进此代码? 答案是:

Agent1 must inherit from Agent2, and Agent1 will execute actOn(o,i) using actOn(o), and also delete the repeat function.....

但在我看来,以下答案看起来正确但错误,原因:

" Agent2 must inherit from Agent1, and Agent2 will execute actOn(o) using actOn(o,i), and also delete the repeat function"

编辑:大胆 Agent2

第一个选项:

Agent1 must inherit from Agent2, and Agent1 will execute actOn(o,i) using actOn(o), and also delete the repeat function.....

可能的实现:

public abstract class Agent1 extends Agent2{
    public void actOn(Object o, int i){
        // do something with i
        actOn(o);
    }
    public abstract void actOn(Object o);
}

public abstract class Agent2 {
    public abstract void actOn(Object o, int i);
    public void repeat(Object o, int i) {
        for (int j = 1; j <= i; j++) {
            actOn(o, j);
        }
    }
}

第二个选项:

" Agent2 must inherit from Agent1, and Agent1 will execute actOn(o) using actOn(o,i), and also delete the repeat function"

Agent1 在执行 actOn(o) 时不能使用 actOn(o,i) 因为如果 Agent2 extends Agent1 那么 Agent2 将继承自 Agent1(反之亦然),因此 actOn(o,i) Agent1 将无法使用。

第二个选项错误,第一个正确。

第二个选项 编辑:

" Agent2 must inherit from Agent1, and Agent2 will execute actOn(o) using actOn(o,i), and also delete the repeat function"

实施尝试:

public abstract class Agent2 extends Agent1{
    public void actOn(Object o){

        actOn(o, i); // what is i ???
    }
    public abstract void actOn(Object o, int i);
}

public abstract class Agent1 {
    public abstract void actOn(Object o);
    public void repeat(Object o, int i) {
       for (int j = 1; j <= i; j++) {
           actOn(o);
       }
    }
}

如您所见,您无法在 Agent2 class 中从 actOn(o) 调用 actOn(o, i),除非您先声明并初始化 i。如果练习没有对创建额外变量设置任何限制,那么我看不出第二个答案有什么问题。