extends League{ ... 如何创建此类的实例? ChampionsLeague league = new ChampionsL-6ren">
gpt4 book ai didi

java - 如何创建通用子类的实例?出现错误 : "Bound mismatch: The type ... is not a valid substitute for the bounded parameter ..."

转载 作者:行者123 更新时间:2023-12-02 05:56:05 30 4
gpt4 key购买 nike

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

如何创建此类的实例?

ChampionsLeague<Team> league = new ChampionsLeague<>();

这不起作用:

"Bound mismatch: The type Team is not a valid substitute for the bounded parameter <Team extends Comparable<Team>> of the type ChampionsLeague<Team>"

最佳答案

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

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

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

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> {

关于java - 如何创建通用子类的实例?出现错误 : "Bound mismatch: The type ... is not a valid substitute for the bounded parameter ...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17018066/

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