如何为其他泛型类声明抽象泛型超类?

时间:2013-06-09 20:30:43

标签: java class generics superclass

如何为其他泛型类声明抽象泛型超类?

    public class CampionsLeague<Team> extends League<Team> {
    ...

League<Team>我收到错误:

  

“绑定不匹配:Team类型不是有效参数的有效替代品&lt; Team extends Comparable&lt; Team&gt;&gt;类型为League&lt; Team&gt;”

2 个答案:

答案 0 :(得分:3)

由于错误明确指出,除非League<X>满足X声明中声明的约束,否则不能写League

您需要约束派生类的泛型参数以匹配基类中的约束:

public class ChampionsLeague<Team extends Comparable<Team>> extends League<Team>

答案 1 :(得分:-2)

如果你有通用类

class League<T extends Comparable<T>>

并且您想要创建其通用子类,您必须确保满足所有约束:

class ChampionsLeague<T extends Comparable<T>> extends League<T>

但是当你想用提供的泛型类子类时,例如有一个类:

class Team implements Comparable<Team>

您不应在派生类名称中重复此类型:

class ChampionsLeague extends League<Team>

这样的事情:

class ChampionsLeague<Team> extends League<Team>
class ChampionsLeague<Team extends Comparable<Team>> extends League<Team>
编译器将

视为由新占位符隐藏League的先前泛型类型。幸运的是,你应该被IDE警告,你可以看到这样的东西:

The type parameter Team is hiding the type Team.