【发布时间】:2016-07-24 11:57:51
【问题描述】:
假设我们有一个带有 compare() 函数的 Parent 接口。
public interface Parent {
public int compare(Parent otherParent);
}
假设孩子Child1、Child2、Child3实现了这个接口Parent
public class Child1 implements Parent {
@Override
public int compare(Parent other) {
Child1 otherChild = (Child1)other;
}
}
另外,我在代码中的其他任何地方都使用泛型<T extends Parent>。所以我需要从代码的其他部分比较两个类型为 T 的对象。
我知道这是一个糟糕的设计,因为我在 compare() 函数中对 Parent 对象进行类型转换,我什至不知道输入是否属于 Child1 类型。
在使用泛型时如何避免这种类型转换?
【问题讨论】:
标签: java generics casting polymorphism