将父对象分配给子对象而不用Java进行转换 [英] Assigning a Parent object to a Child object Without casting in Java

查看:214
本文介绍了将父对象分配给子对象而不用Java进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象要实现的父接口和子接口。我做了一个子接口,因为我想要一个特定的VehicleEntity对象,例如 Truck ,将自身添加到 Car 的HashMap中。 。 卡车将调用VehicleManager的 addToCar()方法,该方法将Truck对象添加到Car的hashMap中。我遇到的问题是 CarEntity ce = ve; 。 Netbeans告诉我将 ve 投射到CarEntity,但我不想这么做。该行代码是否有效(假设for循环正在查看的对象是Car对象)?我该如何解决?

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
        }
    }
}


推荐答案

真的,那根本无效。您可以从特定对象迁移到一般对象而无需强制转换,但不能再次返回。例如,您可以将ArrayList存储在List变量中,但不能将List放入不进行强制转换的ArrayList变量中。同样,在没有明确铸造的情况下,您也无法乘坐汽车并说这是一辆汽车。

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.

这篇关于将父对象分配给子对象而不用Java进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆