You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
1.5 KiB
42 lines
1.5 KiB
package w5挑战版;
|
|
|
|
import java.util.List;
|
|
import java.util.ArrayList;
|
|
|
|
// 人员管理器(重构关键)
|
|
public class PersonManager {
|
|
// 用List存储Person,容纳所有子类对象
|
|
private List<Person> personList = new ArrayList<>();
|
|
|
|
// 核心重构:合并成一个方法,接收父类引用
|
|
public void addPerson(Person person) {
|
|
personList.add(person);
|
|
System.out.println("添加成功:" + person.getClass().getSimpleName());
|
|
}
|
|
|
|
// 显示所有人信息(多态调用)
|
|
public void showAllPersons() {
|
|
System.out.println("\n=== 所有人员列表 ===");
|
|
for (Person p : personList) {
|
|
p.showInfo();
|
|
}
|
|
}
|
|
|
|
// 解决特定属性问题:使用instanceof判断类型并获取属性
|
|
public void checkPersonDetails() {
|
|
System.out.println("\n=== 人员详情检查 ===");
|
|
for (Person p : personList) {
|
|
if (p instanceof Student) {
|
|
Student s = (Student) p;
|
|
// 现在Student有了getStudentId(),就不会报错了
|
|
System.out.println(s.getName() + " 是学生,学号:" + s.getStudentId());
|
|
} else if (p instanceof Teacher) {
|
|
Teacher t = (Teacher) p;
|
|
// 现在Teacher有了getTeacherId(),就不会报错了
|
|
System.out.println(t.getName() + " 是老师,工号:" + t.getTeacherId());
|
|
} else {
|
|
System.out.println(p.getName() + " 是普通人员");
|
|
}
|
|
}
|
|
}
|
|
}
|