本帖最后由 noiary 于 2014-10-9 21:41 编辑
突然地不确定List<Person>集合通过add方法装入Person对象后还能不能装入Person的子类
所以写个代码求证一下
发来分享- /**
- * 测试List集合指定Person类型之后是否可以装入子类Employee
- * 或者装入Employee对象后是否可以装入父类Person
- */
- package day17_Collections;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * @author Administrator
- *
- */
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- GenericTest1();
- }
-
- /*
- * 泛型定义Person类型后装入子类Employee测试
- */
- public static void GenericTest1() {
- List<Person> list = new ArrayList<Person>();
- list.add(new Person("郭敬明", 35));
- list.add(new Person("張小莉", 28));
- list.add(new Person("習大大", 55));
- list.add(new Employee("杜海涛", 32, "12345"));
- for (Person p : list) {
- System.out.println(p);
- }
- }
-
- /*
- * 泛型定义Employee类型后装入子类Person测试
- * 无法通过 orz
-
- public static void GenericTest2() {
- List<Employee> list = new ArrayList<Employee>();
- list.add(new Person("郭敬明", 35));
- list.add(new Person("張小莉", 28));
- list.add(new Person("習大大", 55));
- list.add(new Employee("杜海涛", 32, "12345"));
- for (Person p : list) {
- System.out.println(p);
- }
- }
- */
- }
- 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;
- }
- public String toString() {
- return this.getClass().getName() + " 姓名:" + name + "|年龄:" + age;
- }
- }
- class Employee extends Person {
- private String id;
- Employee(String name, int age, String id) {
- super(name, age);
- this.id = id;
- }
- public String toString() {
- return this.getClass().getName() + " 姓名:" + super.getName() + "|年龄:"
- + super.getAge() + "|学号:" + id;
- }
- }
复制代码
|