【问题标题】:How super keyword work with Object超级关键字如何与 Object 一起使用
【发布时间】:2015-10-07 23:32:26
【问题描述】:

我为 Runnable 接口使用 super 并定义 Object 类型来存储没有得到任何编译错误,但对于下面的代码 MyRunnale(i) 正在使用 MyObject 存储但编译器引发编译错误:类型不匹配
请解释一下为什么会出现编译错误以及为什么会出现错误。

class Test 
{

    public static void main(String[] args) {
        ArrayList<? super Runnable> a1 = new ArrayList<Object>();
        // Here am not getting any CTE but for the below code
        ArrayList<? super MyRunnable> a2 = new ArrayList<MyObject>();
        // compile error: Type mismatch: cannot convert from ArrayList<MyObject> to
        // ArrayList<? super MyRunnable>
    }
}

class MyObject {
}
interface MyRunnable {
}
class MyThread extends MyObject implements MyRunnable {
}

【问题讨论】:

  • extends相反。所以它需要一个超类而不是子类。
  • 请不要使用 TLA,除非它们是常用的。

标签: java object generics superclass super


【解决方案1】:

当您使用ArrayList&lt;? super Runnable&gt; 时,表示ArrayList 可以引用RunnableRunnable 的任何超类型(在本例中为ArrayList&lt;Runnable&gt;()ArrayList&lt;Object&gt;())的ArryList。

但是MyObjectRunnable 的子类型。因此,它不允许您为其分配 ArrayList&lt;MyObject&gt;()

如果你想引用ArrayList&lt;MyObject&gt;(),你应该使用ArrayList&lt;? extends Runnable&gt;

但请确保您满足PECS 规则。

【讨论】:

  • 这意味着 ArrayList 将接受 Runnable 和任何超类型的 Runnable。这里的措辞有点模棱两可,因为add 方法实际上可以接受任何实现Runnable 的类。 (ArrayList 可以接受任何 is-a Runnable 的类会更正确)
  • 如何让 MyObject 接受存储在 MyRunnable 中?你能建议我任何代码参考吗?
猜你喜欢
  • 2023-03-23
  • 2020-10-12
  • 2011-02-05
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多