[英]How super keyword work with Object
在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>()
但是MyObject
是Runnable
的子類型。 因此,它不允許您為其分配ArrayList<MyObject>()
。
如果要引用ArrayList<MyObject>()
,則應使用ArrayList<? extends Runnable>
ArrayList<? extends Runnable>
。
但是,請確保滿足PECS規則。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.