利用继承关系,设计名为Person、小学生PupilStudent、研究生GraduateStudent三个类,其中每个类都有toString方法返回各自的类型信息。PupilStudent有上学方法GoToSchool,GraduateStudent有从事项目方法DoProject;根据多态性,使用ArrayList链表将各个对象放入其中。利用循环取出链表中的元素,根据类型调用相应的方法。最后清空链表中的元素
时间: 2023-05-27 10:03:11 浏览: 172
代码如下(Java语言):
Person类:
```
public class Person {
@Override
public String toString() {
return "Person";
}
}
```
PupilStudent类:
```
public class PupilStudent extends Person {
public void goToSchool() {
System.out.println("PupilStudent goes to school.");
}
@Override
public String toString() {
return "PupilStudent";
}
}
```
GraduateStudent类:
```
public class GraduateStudent extends Person {
public void doProject() {
System.out.println("GraduateStudent does project.");
}
@Override
public String toString() {
return "GraduateStudent";
}
}
```
测试代码:
```
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new PupilStudent());
list.add(new GraduateStudent());
list.add(new PupilStudent());
for (Person p : list) {
System.out.println(p.toString());
if (p instanceof PupilStudent) {
((PupilStudent)p).goToSchool();
} else if (p instanceof GraduateStudent) {
((GraduateStudent)p).doProject();
}
}
list.clear();
}
}
```
输出结果:
```
PupilStudent
PupilStudent goes to school.
GraduateStudent
GraduateStudent does project.
PupilStudent
PupilStudent goes to school.
```
阅读全文