Java多态:如何避免类型转换输入参数?

Aja*_*pta 7 java generics polymorphism casting

假设我们有一个带compare()函数的Parent接口.

public interface Parent {
    public int compare(Parent otherParent);
}
Run Code Online (Sandbox Code Playgroud)

假设子项Child1,Child2,Child3实现此接口Parent

public class Child1 implements Parent {
    @Override
    public int compare(Parent other) {
        Child1 otherChild = (Child1)other;
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,我<T extends Parent>在代码中的其他地方使用泛型.所以我需要从代码的其他部分比较两个类型为T的对象.

我理解这是一个糟糕的设计,因为我在compare()函数中类型化了Parent对象,我甚至不知道输入是否是Child1类型.

在使用泛型时如何避免这种类型的转换?

Ped*_*vid 5

为什么不呢?

interface Parent<T extends Parent<?>> {
    int compare(T type);
}

class Child1 implements Parent<Child1>{

    @Override
    public int compare(Child1 type) {
        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑: 为确保正确使用,您可以使用

interface Parent<T extends Parent<T>>{ /* ... */ }   //instead of wildcard
Run Code Online (Sandbox Code Playgroud)

但说实话,"循环"看起来并不漂亮,而且由于Java中的Generics在RunTime上不起作用(更多信息),它们基本上是语法糖,因为你称之为"糟糕设计"的同一个演员,所以我不喜欢我认为你目前的做法很糟糕.


Mar*_*ler 2

你不能。Java 接口正是顾名思义 \xe2\x80\x93 一个规定接受类型的接口;因此,编译时需要与接口中定义的方法签名完全相同。

\n\n

是的,将其转换回 Child 类型感觉像是糟糕的设计 \xe2\x80\x93 但这确实是 Java 规定的糟糕设计,所以这不是你的错。

\n