gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:08:15 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com