您可以通过以下方式进行:
import java.util.ArrayList;
import java.util.List;
abstract class Parent {
void callMe(){
System.out.println("Parent");
}
}
class Child extends Parent {
void callMe(){
System.out.println("Child");
}
}
public class TestClass {
public static void main(String[] args) {
List<Parent> alist=new ArrayList<Parent>();
List<? super Child> alist2=alist;
}
}
Run Code Online (Sandbox Code Playgroud)
List<Parent>
与 不同List<Child>
。Compilor不允许的参考分配List<Parent>
到List<Child>
即使列表只包含子对象。
例如:
List<Parent> parentList=new ArryList<Parent>();
parentList.add(new Child());
parentList.add(new Child());
parentList.add(new Child());
//This is not allowed
List<Child> childList=(List<Child>)parentList;//Compiler Error
//But,This is allowed
List<? super Child> childList=parentList; //Okey
Run Code Online (Sandbox Code Playgroud)
这是允许的,因为使用List<? super Child>
保证List<Parent>
不会损坏的参考。
归档时间: |
|
查看次数: |
3185 次 |
最近记录: |