请考虑以下代码:
public class Vehicle{
private int pos_x;
private int pos_y;
public void update(float delta){
move(delta); // function move() isn't shown here but modifies pos_x and pos_y
}
}
public class Car extends Vehicle{
private int speed = 10;
@Override
public void update(float delta){
super.update(delta * speed);
}
}
public class Tank extends Vehicle{
private int speed = 3;
private int munitions = 100;
@Override
public void update(float delta){
super.update(delta * speed);
}
public void shoot(){
// Do something
}
}
public void main(String[] args){
List<Vehicle> vehicles = new ArrayList<Vehicle>();
vehicles.add(new Car());
vehicles.add(new Tank());
while(true){
float delta = getElapsedTimeSinceLastLoop(); // not shown
for(Vehicle v : vehicles){
v.update(delta);
if(playerIsHoldingDownShootButton())((Tank)v).shoot();
}
sleep(); // not shown
}
}如果我不尝试把v转换成坦克,我就无法访问射击()函数。如果我试图将v投给坦克,我会得到一个错误,因为车辆列表中包含一辆汽车,而这辆车不能投给坦克。我能避免错误的唯一方法是测试是否(坦克的实例),然后将其转换为坦克。
但是,如果我有很多不同功能的车辆类型呢?
编辑:多亏@斯卡沃姆巴特,我重写了这个问题,以更接近我的实际问题。
发布于 2017-10-25 09:17:19
在主方法中,只需调用所有车辆的update()即可。让坦克自己决定是否用自己的更新方法射击。
https://stackoverflow.com/questions/46927350
复制相似问题