super 关键字如何与 Object 一起使用
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 可以引用 Runnable
的 ArryList 和 Runnable
的任何超类型(在这种情况下 ArrayList<Runnable>()
或 ArrayList<Object>()
).
但是MyObject
是Runnable
的子类型。因此,它不允许您为其分配 ArrayList<MyObject>()
。
如果你想参考ArrayList<MyObject>()
,你应该使用ArrayList<? extends Runnable>
。
但请确保您满足 PECS 规则。
我正在为 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 可以引用 Runnable
的 ArryList 和 Runnable
的任何超类型(在这种情况下 ArrayList<Runnable>()
或 ArrayList<Object>()
).
但是MyObject
是Runnable
的子类型。因此,它不允许您为其分配 ArrayList<MyObject>()
。
如果你想参考ArrayList<MyObject>()
,你应该使用ArrayList<? extends Runnable>
。
但请确保您满足 PECS 规则。