【问题标题】:How do I make an instance of generic subclass? Getting error: "Bound mismatch: The type ... is not a valid substitute for the bounded parameter ..."如何创建泛型子类的实例?出现错误:“绑定不匹配:类型......不是有界参数的有效替代品......”
【发布时间】:2013-06-10 06:33:21
【问题描述】:
public class ChampionsLeague<Team extends Comparable<Team>> extends League<Team>{
...

如何创建此类的实例?

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

这不起作用:

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

【问题讨论】:

    标签: java class generics object


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 是的,泛型有时真的很棘手。我添加了一些建议以进一步帮助您。让我知道您是否解决了这两个问题(了解错误并首先得到您想要的)。
    • @PeterBauer:这意味着您的问题(就目前而言)不能帮助您解决问题(并且可能不会帮助其他人),所以我会投票关闭“过于本地化” .这并不意味着这是一个糟糕的问题,只是(就目前而言)它可能会使其他人感到困惑而不是帮助。
    • @JoachimSauer 这可能对其他人有帮助 “绑定不匹配:类型 (...) 不是有界参数 (...) 的有效替代品”我>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 2020-04-14
    相关资源
    最近更新 更多