I have a parent interface and a child interface which objects will implement. I’ve made a child interface because I want a specific VehicleEntity object say Truck to add itself to the HashMap in Car. A Truck will call VehicleManager’s addToCar() method which add the Truck object into Car’s hashMap. The issue I have is CarEntity ce = ve;. Netbeans is telling me to cast ve to CarEntity but I don’t want to. Shouldn’t the line of code be valid (assuming the the object the for loop is looking at is a Car object)? How can I fix this?
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
}
}
}
Really, that’s not at all valid. You can move from the specific to the general without casting, but not back again. For instance, you can store an ArrayList in a List variable, but you can’t take a List and put it into an ArrayList variable without casting. In the same way, you can’t take a vehicle and say it is a car without explicitly casting.
So, in this case, since you know the vehicle is a car, cast to a car explicitly.