将父对象分配给Child对象而不在Java中进行强制转换

时间:2011-10-26 21:20:48

标签: java inheritance casting

我有一个父接口和一个子接口,对象将实现。我创建了一个子接口,因为我想要一个特定的VehicleEntity对象说Truck将自己添加到Car中的HashMap。 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
        }
    }
}

2 个答案:

答案 0 :(得分:5)

真的,这根本不是有效的。您可以在不进行转换的情况下从特定转移到常规,但不能再转回。例如,您可以将ArrayList存储在List变量中,但是您无法获取List并将其放入ArrayList变量中而不进行强制转换。以同样的方式,你不能拿车并说它是没有明确铸造的汽车。

因此,在这种情况下,因为您知道车辆是汽车,所以明确地投入汽车。

答案 1 :(得分:0)

我不完全确定你要到达的是什么,所以我要先用最好的猜测列出一些纠正的课程......

public interface VehicleEntity {

    public String getId();

    public String getSpeed();

    public void move();

}

public interface CarEntity extends VehicleEntity {

    public void addToCar(String key, CarEntity c);

}

import java.util.HashMap;

public class Car implements CarEntity{ 
HashMap<String, VehicleEntity> cars = new HashMap<String, VehicleEntity>();

    @Override
    public void addToCar(String key, CarEntity car) {
       cars.put(key, this);
    }

    @Override
    public String getId() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String getSpeed() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void move() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

...然后使用泛型显示一个很酷的技巧:

import java.util.HashMap;

public class VehicleManager {

    HashMap<String, VehicleEntity> vehicles =
        new HashMap<String, VehicleEntity>();

    public <T extends VehicleEntity> T report(String id) {
        for(VehicleEntity ve : vehicles.values()) {
            if(ve.getId().equals(id)) {
                @SuppressWarnings("unchecked")
                T ce = (T)ve;
                return ce;
            }
        }
        return null;
    }

    public void test() {

        final Car c = report("test");

    }

}

我已使用report扩展T参数化了方法VehicleEntity。它将返回该类型的T。在方法test()中使用此功能时,我们已声明我们需要Car。现在,一些类型推断将继续进行,为类型report自动调用方法Car。如果具有给定id的地图中的VehicleEntity不是Car,我们将获得ClassCastException,因为我们在该上下文中调用thet方法时尝试强制转换为Car