Java 多态性 : How can I avoid type casting input parameters?

标签 java generics casting polymorphism

假设我们有一个带有 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/

相关文章:

java - 在 java 属性声明中强制使用泛型类型

php - Laravel 5 Eloquent,如何动态设置 cast 属性

C++ 重新解释_cast

IOS是否可以在不强制转换的情况下获取NSFetchedResultsController字段的数据

java - 如何访问 JavaFX 中的 DatePicker 值以进行 SELECT MySQL 查询?

java - 尝试查找 WebElement 时出现 NullpointerException

java - 如何阻止 wordwrapped-JTextArea 调整大小以适应大内容?

java - 类、方法及其成员存储在内存中的什么位置?

java - 什么是 PECS(生产者扩展消费者 super )?

java - 为什么我不能捕获抛出泛型的调用的已检查异常?