class Person1{
private String name;
public Person1(String name){
this.name=name;
}
public String getName(){
return name;
}
}
class Student1 extends Person1{
public Student1(String name){
super(name);
}
}
public class GenericDemo {
public static void main(String[] args) {
ArrayList<Person1> al=new ArrayList<Person1>();
al.add(new Person1("zhagnsan1"));
ArrayList<Person1> al1=new ArrayList<Person1>();
al1.add(new Student1("liming1"));
printArr(al1);
}
//利用泛型限定,上限
public static void printArr(ArrayList<? extends Person1> al){
Iterator<? extends Person1> it=al.iterator();
while(it.hasNext()){
System.out.println(it.next().getName());
}
}
//下限
public static void print2(ArrayList<? super Student1> al){
Iterator<? super Student1> it=al.iterator();
while(it.hasNext()){
System.out.println(it.next().getName());
}
}
}
在向下限定时Student1类继承了Person1类,而Person1类中有getName方法,那么it.next().getName()为什么不正确?
|