import java.util.*;
class GenericDemo4
{
public static void main(String[] args)
{
ArrayList<Person> a = new ArrayList<Person>();
a.add(new Person("lili",17));
a.add(new Person("lili",18));
a.add(new Person("lili",19));
ArrayList<Student> b = new ArrayList<Student>();
b.add(new Student("lisi",17));
b.add(new Student("lisi",8));
b.add(new Student("lisi",19));
printColl(a);
System.out.println("----------------");
printColl(b);
}
public static void printColl(ArrayList<Person> a)//这里失败了 为什么不能用父类的
//下面的next方法返回的是对象那么父类引用指向子类对象不是可行么?
{
Iterator<Person> it = a.iterator();
while (it.hasNext())
{
Person p = it.next();
System.out.println(p.getName()+"..."+p.getAge());
}
}
}
class Person
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class Student extends Person
{
Student(String name,int age)
{
super(name,age);
}
}
|