java - 如何将 Iterable<interface> 返回类型方法重写为 Iterable<?扩展接口(interface)>返回类型方法

标签 java oop generics overriding decorator

我有一个需要实现的接口(interface)。它看起来像这样:

public interface SimulationState {
    ...
    public Iterable<VehicleStatus> getVehicleStatuses();
}

我正在尝试将接口(interface)扩展为某种装饰器接口(interface),如下所示:

public interface SimulationStateDec<V extends VehicleStatus> extends SimulationState {
    ...
    @Override
    public Iterable<V> getVehicleStatuses();
}

public interface SimulationStateDec<V extends VehicleStatus> extends SimulationState {
    ...
    @Override
    public Iterable<? extends VehicleStatus> getVehicleStatuses();
}

这是我实现接口(interface)的具体类:

public class WareHouseState implements SimulationState {
    ...       
    @Override
    public Iterable<VehicleStatus> getVehicleStatuses() {
    return this.vStatuses;
   }
}

我在名为 VehicleState 的类中实现了 VehicleStatus 接口(interface),因此我可以返回已实现的 VehicleState 虽然我的具体类中的 Iterable

所以在我项目的一个类中,我调用了 getVehicleStatuses() 方法 我有义务将每个元素转换为 VehicleState,如下所示:

public class Gate {
    ...
    private ArrayList<VehicleThread> vehicles;

    public Gate(WareHouse wareHouse, GatePriority priority) {
        ...
        this.vehicles = new ArrayList<>();
        wareHouseState.getVehicleStatuses().forEach(v -> vehicles.add(new VehicleThread((VehicleState) v, wareHouse)));
        sortSameTimeArrivalBy(priority);

    }
}

我知道我在这里做错了,我想知道是否允许这种实现方式。 编译器告诉我更改已实现接口(interface)中的方法,但它不适用于我的应用程序必须在不同的框架上工作。

我需要返回实现相同接口(interface)的各种具体类型,而不必转换每个元素。

最佳答案

你不能,因为重写时你只能缩小返回类型的范围,Iterable<V> 都不是也不Iterable<? extends VehicleStatus>Iterable<VehicleStatus> 的子类型.

在 Java 8 中,您或许可以添加新方法而不覆盖并将旧方法实现为默认方法(或在以前的版本中使用抽象类):

public interface SimulationStateDec<V extends VehicleStatus> extends SimulationState {
    ...
    Iterable<V> getVehicleStatusesDec();

    default Iterable<VehicleStatus> getVehicleStatuses() {
        return (Iterable<VehicleStatus>) getVehicleStatusesDec();
    }
}

这应该是安全的,因为 Iterable<T>没有任何采用 T 的方法作为参数:它“应该”是协变的,除非 Java 不支持;对例如做同样的事情List这是个坏主意!

关于java - 如何将 Iterable<interface> 返回类型方法重写为 Iterable<?扩展接口(interface)>返回类型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40442258/

相关文章:

java - 无法反序列化 `org.json.JSONObject` 的实例

c++ - 如何从 CPP 中的头文件访问枚举

ios - 测试定义为 Any 的值的数组包含,但保证属于同一类型。

c# - 使用泛型更新特定属性 (Winform C#)

java - 查找平面上两点之间的距离(由笛卡尔坐标给出)

java - 强制子类重写以自身为参数的方法

java - 使用\n 作为分隔符打印一个额外的空行

c# - 如何避免在变量赋值的情况下调用冗余?

c++ - 在容器中存储多重继承对象

java - 为什么编译类型不匹配?使用接口(interface)时扩展