Dan*_*Dan 1 java inheritance casting
我有一个父接口和一个子接口,对象将实现.我已经创建了一个子接口,因为我希望一个特定的VehicleEntity对象说Truck要将自己添加到HashMap中Car.A Truck将调用VehicleManager的addToCar()方法,将Truck对象添加到Car的hashMap中.我遇到的问题是CarEntity ce = ve;.Netbeans告诉我施放ve给CarEntity,但我不想.代码行不应该有效(假设for循环正在查看的对象是Car对象)?我怎样才能解决这个问题?
public interface VehicleEntity {
getId();
getSpeed();
move();
}
public interface CarEntity extends VehicleEntity{
addToCar(String c);
}
public class Car implements CarEntity{
HashMap<String, VehicleEntity> cars = new HashMap<String, VehicleEntity>();
public void addToCar(String c) {
cars.add(c);
}
}
public class VehicleManager {
HashMap<String, VehicleEntity> vehicles = new HashMap<String, VehicleEntity>();
public void reportToCar(String id) {
for (VehicleEntity ve : ve.values()) {
if (ve.getId().equals(id)) {
CarEntity ce = ve; // Issue here
}
}
}
Run Code Online (Sandbox Code Playgroud)
真的,这根本不是有效的.您可以在不进行投射的情况下从特定位置移动到常规位置,但不能再次返回.例如,您可以将ArrayList存储在List变量中,但是您无法获取List并将其放入ArrayList变量中而不进行强制转换.以同样的方式,你不能拿车,并说它是一辆没有明确铸造的汽车.
因此,在这种情况下,因为您知道车辆是汽车,所以明确地投入汽车.
| 归档时间: |
|
| 查看次数: |
5689 次 |
| 最近记录: |