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);
}
}
}
How this code can be improved, by means of reducing code duplication? the answer says:
Agent1 must inherit from Agent2, and Agent1 will execute actOn(o,i) using actOn(o), and also delete the repeat function.....
BUT in my opinion the following answer look correct but its wrong, why:
" Agent2 must inherit from Agent1, and Agent2 will execute actOn(o) using actOn(o,i), and also delete the repeat function"
EDIT: THE BOLD Agent2
First option:
Agent1 must inherit from Agent2, and Agent1 will execute actOn(o,i) using actOn(o), and also delete the repeat function.....
Possible implementation:
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);
}
}
}
Second option:
" Agent2 must inherit from Agent1, and Agent1 will execute actOn(o) using actOn(o,i), and also delete the repeat function"
Agent1 cannot use actOn(o,i)
when executing actOn(o)
because if Agent2 extends
Agent1 then Agent2 will be the one inheriting from Agent1 (not viceversa), therefore the actOn(o,i)
won't be available to Agent1.
The second option is wrong, the first one is correct.
Second option EDIT:
" Agent2 must inherit from Agent1, and Agent2 will execute actOn(o) using actOn(o,i), and also delete the repeat function"
Implementation attempt:
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);
}
}
}
As you can see you are not able to call actOn(o, i)
from actOn(o)
within the Agent2 class unless you declare and initialize i
first. If the excercise did not set any restriction about creating extra variables, then I can't see anything wrong with the second answer.