【发布时间】: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