当前位置: 代码迷 >> java >> 超级关键字如何与对象一起使用
  详细解决方案

超级关键字如何与对象一起使用

热度:34   发布时间:2023-08-02 10:20:05.0

在Runnable接口上使用super并定义对象类型来存储没有得到任何编译错误,但是对于以下代码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 {
}

当您使用ArrayList<? super Runnable> ArrayList<? super Runnable> ,这意味着该ArrayList可以指的ArryList Runnable和任何超类型的Runnable (在此情况下ArrayList<Runnable>()ArrayList<Object>()

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

如果要引用ArrayList<MyObject>() ,则应使用ArrayList<? extends Runnable> ArrayList<? extends Runnable>

但是,请确保满足规则。

  相关解决方案