首先你的主函数少了个括号,你是不想定义一个用泛型定义的打印方法,来实现打印集合中,Person和Student对象,代码如下:
import java.util.*;
class GenericDemo6
{
public static void main(String [] args)
{
ArrayList<Person> a1=new ArrayList<Person>();
a1.add(new Person("abc01"));
a1.add(new Person("abc02"));
a1.add(new Person("abc03"));
printColl(a1);
ArrayList<Student> a11=new ArrayList<Student>();
a11.add(new Student("abc---01"));
a11.add(new Student("abc---02"));
a11.add(new Student("abc---03"));
printColl(a11);
}
public static void printColl(ArrayList<? extends Person> a1)
{
Iterator<? extends Person> it=a1.iterator();
while(it.hasNext())
{
System.out.println(it.next().getName());
}
}
}
class Person
{
private String name;
Person(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
class Student extends Person
{
Student(String name)
{
super(name);
}
} |