public class Person {
private long id;
private String name;
private int age;
public Person() {
super();
}
public Person(long id, String name,int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
setter、getter方法
}
子类
package test;
public class Student extends Person {
private String schoolName;
private String xueHao;
public Student() {
super();
}
public Student(long id, String name, int age, String schoolName, String xueHao) {
super(id, name, age);
this.schoolName = schoolName;
this.xueHao = xueHao;
}
setter、getter方法
}
测试类
package test;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
/**
* Person 类有3个属性
* Student 类继承了Person类,并添加了2个属性
* 把Person类的list集合中的元素放在Student类的list集合中
*/
父类集合
List<Person> ps = new ArrayList<>();
Person ps1 = new Person(1, "a", 11); ps.add(ps1); 把实例化添加到父类集合中
Person ps2 = new Person(2, "b", 12); ps.add(ps2);
Person ps3 = new Person(3, "c", 13); ps.add(ps3);
Person ps4 = new Person(4, "d", 14); ps.add(ps4);
创建子类集合
List<Student> st = new ArrayList<>();
实例化子类对象
for(int j =0;j<ps.size();j++) {
Student stu = new Student();
获取父类的属性值
stu.setId(ps.get(j).getId());
stu.setName(ps.get(j).getName());
stu.setAge(ps.get(j).getAge());
设置子类的属性值
stu.setSchoolName(null);
stu.setXueHao(null);
st.add(stu);
}
for(int i=0;i<st.size();i++) {
System.out.println("姓名:"+st.get(i).getName()+", 学校:"+st.get(i).getSchoolName());
}
}
}