我目前正在开发一个需要我控制机器人的项目。
我将它们保存在RobotInterfaces数组中,事实上,我有一个名为RobotMovement的超级类,因为所有机器人的所有运动都是相同的。
实现RobotInterface的机器人类也扩展了Super Class
如何从接口数组中的超类调用方法move()?
答案 0 :(得分:1)
实现RobotInterface的机器人类也扩展了Super Class
如何从接口数组中的超类调用方法move()?
您可以在move()
中声明RobotInterface
方法。这样,Java将允许您对move()
类型的任何表达式调用RobotInterface
,Java将强制要求RobotInterface
的所有实例都具有move()
的实现。
答案 1 :(得分:1)
class RobotMovement {
public void move() {
System.out.println("moving...");
}
}
interface RobotInterface {
public void move(); // add this
}
class Robot extends RobotMovement implements RobotInterface {
}
class Main {
public static void main(String[] args) {
List<RobotInterface> list = new ArrayList<RobotInterface>();
list.add(new Robot());
list.add(new Robot());
for (RobotInterface ri: list) {
ri.move();
}
}
}