I have a class called Thing
and a class called Robot
. Thing
has a public void setBlocksExit()
. Robot
has some methods I also desire.
I have extended Robot
but I also want setBlocksExit()
from Thing
. I would make an interface that has setBlocksExit()
and then make a class like:
public class C extends Robot implements BlockExit {}
The problem is I don't have access to the source code for Thing
and Robot
. I am using an educational package 'becker.jar' and all of the code is compiled so I can't access it to extract interfaces. What are my options?
Your options are the following:
Thing
and have a reference to a Robot
which you delegate all Robot
methods to.Robot
and have a reference to a Thing
object which you delegate setBlocksExit
calls to.Robot
and a reference to a Thing
and delegate calls to these two objects.If you're using an IDE such as Eclipse you can even "extract interfaces" and generate delegate methods automatically.
Option 1:
class C extends Thing {
final Robot robot;
public C(Robot robot) {
this.robot = robot;
}
public int robotMethod1() {
return robot.robotMethod1();
}
...
}
Option 2:
class C extends Robot {
final Thing thing;
public C(Thing thing) {
this.thing = thing;
}
public void setBlocksExit(boolean flag) {
return thing.setBlocksExit(flag);
}
...
}
Option 3:
class C {
final Thing thing;
final Robot robot;
public C(Thing thing, Robot robot) {
this.thing = thing;
this.robot = robot;
}
public void setBlocksExit(boolean flag) {
return thing.setBlocksExit(flag);
}
public int robotMethod1() {
return robot.robotMethod1();
}
...
}
If you're using Eclipse you could use this feature:
I'm sure whatever IDE you're using has a similar feature.