声明测试类完成对多态性的测试 在主方法中声明Student类的数组(含5个元素);生成五个对象存入数组:其中三个Student类的对象,一个StudentXW的对象,一个Studentbz类的对象;将方法testScore()发给数组的每一个元素,输出结果,并分析具体执行的是哪一个类中的方法
时间: 2024-02-25 11:55:50 浏览: 16
好的,下面是示例代码:
```java
public class TestPolymorphism {
public static void main(String[] args) {
// 声明Student类的数组(含5个元素)
Student[] students = new Student[5];
// 生成五个对象存入数组
students[0] = new Student("Tom", 18, 85);
students[1] = new Student("Jerry", 19, 90);
students[2] = new Student("Mary", 20, 95);
students[3] = new StudentXW("小王", 21, 80, 90);
students[4] = new StudentBZ("小张", 22, 70, 80, 90);
// 将方法testScore()发给数组的每一个元素,输出结果
for (int i = 0; i < students.length; i++) {
students[i].testScore();
}
}
}
// 学生类
class Student {
protected String name; // 姓名
protected int age; // 年龄
protected int score; // 成绩
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
// 测试成绩的方法
public void testScore() {
System.out.println(name + "的成绩是:" + score);
}
}
// 学生类(小王)
class StudentXW extends Student {
private int score1; // 成绩1
public StudentXW(String name, int age, int score, int score1) {
super(name, age, score);
this.score1 = score1;
}
// 测试成绩的方法(重写)
public void testScore() {
System.out.println(name + "的成绩是:" + (score + score1));
}
}
// 学生类(小张)
class StudentBZ extends Student {
private int score1; // 成绩1
private int score2; // 成绩2
public StudentBZ(String name, int age, int score, int score1, int score2) {
super(name, age, score);
this.score1 = score1;
this.score2 = score2;
}
// 测试成绩的方法(重载)
public void testScore() {
System.out.println(name + "的成绩是:" + (score + score1 + score2));
}
}
```
上述代码中,我们声明了一个 `TestPolymorphism` 类作为测试类,其中在主方法中声明了一个 `Student` 类的数组,包含5个元素。然后,我们生成了五个对象存入数组:其中三个 `Student` 类的对象,一个 `StudentXW` 类的对象,一个 `StudentBZ` 类的对象。最后,我们将方法 `testScore()` 发给数组的每一个元素,输出结果,并分析具体执行的是哪一个类中的方法。
在输出结果时,我们发现,对于普通的 `Student` 类对象,执行的是 `Student` 类中的 `testScore()` 方法;对于 `StudentXW` 类对象,执行的是 `StudentXW` 类中的 `testScore()` 方法;对于 `StudentBZ` 类对象,执行的是 `StudentBZ` 类中的 `testScore()` 方法。这就体现了多态性的特点:在不同的对象上执行同一个方法,会产生不同的行为。