作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
假设我们有一个带有 compare() 函数的 Parent 接口(interface)。
public interface Parent {
public int compare(Parent otherParent);
}
假设 child Child1、Child2、Child3实现了这个接口(interface)Parent
public class Child1 implements Parent {
@Override
public int compare(Parent other) {
Child1 otherChild = (Child1)other;
}
}
此外,我正在使用泛型 <T extends Parent>
代码中的其他地方。所以我需要从代码的其他部分比较两个类型为 T 的对象。
我知道这是一个糟糕的设计,因为我在 compare() 函数中对 Parent 对象进行类型转换,我什至不知道输入是否为 Child1 类型。
如何在使用泛型时避免这种类型转换?
最佳答案
为什么不是这个?
interface Parent<T extends Parent<?>> {
int compare(T type);
}
class Child1 implements Parent<Child1>{
@Override
public int compare(Child1 type) {
return 0;
}
}
编辑:为确保正确使用,您可以使用
interface Parent<T extends Parent<T>>{ /* ... */ } //instead of wildcard
但老实说,“循环”看起来并不漂亮,而且由于 Java 中的泛型在运行时 (more information) 不起作用,它们本质上是你称为“糟糕设计”的同一个类型转换的语法糖"所以我认为您目前的做法还不错。
关于Java 多态性 : How can I avoid type casting input parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38551742/
我是一名优秀的程序员,十分优秀!