当前位置: 首页 > 知识库问答 >
问题:

如何创建泛型子类的实例?获取错误:“绑定不匹配:类型...不是绑定参数...的有效替代。”

吕高雅
2023-03-14
public class ChampionsLeague<Team extends Comparable<Team>> extends League<Team>{
...
ChampionsLeague<Team> league = new ChampionsLeague<>();

这不起作用:

“绑定不匹配:类型team不能有效替代类型 的有界参数

共有1个答案

谢叶五
2023-03-14

在您的代码中,team只是一个占位符(在此上下文中称为类型变量),并且恰好隐藏了类型team,而不是引用它。换言之,该声明相当于:

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

因此,它实际上只要求一个实现(扩展)carable自身的类(或接口)。所以这个例子:

public class Ball implements Comparable<Ball> {
    @Override
    public int compareTo(Ball o) { return 0; }
}
// or: public interface Ball extends Comparable<Ball> { }

将起作用:

ChampionsLeague<Ball> test = new ChampionsLeague<Ball>();
// ChampionsLeague needs a type Comparable to Team
public class ChampionsLeague<T extends Comparable<Team>> extends League<T> {
// ChampionsLeague needs a subtype of Team
// In this case, you can make Team implement Comparable<Team> in its own decl.
public class ChampionsLeague<T extends Team> extends League<T> {
 类似资料: