3、抽象类实现多态设计父类Student、子类小学生Pupil、中学生MiddleStudent、大学生Undergraduate。在文本框输入相关数据,点击按钮,分别输出:² 小学生的姓名、学生类型、平均成绩(语文、数学);² 中学生的姓名、学生类型、平均成绩(语文、数学、英语);² 大学生的姓名、学生类型、总学分(选修课和必修课);² 总人数。(1)Student类(父类、抽象类)² 定义抽象属性Type(学生类型)、静态字段number(学生人数);² 有参构造方法,设置姓名、年龄、统计学生人数;² 抽象方法total()求总分;² 成员方法getInfo(),输出学生姓名、年龄、根据学生类型求平均成绩。(2)子类Pupil、MiddleStudent、Undergraduate² 重写父类的抽象属性Type和抽象方法total();² 定义有参构造方法,设置姓名、年龄、科目,调用父类的构造方法。
时间: 2023-11-17 11:04:11 浏览: 147
设计一个学生类Student(学生学号、姓名、数学、英语、计算机成绩;)
5星 · 资源好评率100%
好的,我理解了你的问题。下面是对应的Java代码实现:
```
// Student类
public abstract class Student {
protected String name;
protected int age;
protected String type;
protected static int number = 0;
public Student(String name, int age) {
this.name = name;
this.age = age;
number++;
}
public abstract double total();
public void getInfo() {
System.out.println("姓名:" + this.name);
System.out.println("年龄:" + this.age);
System.out.println("类型:" + this.type);
}
}
// Pupil类
public class Pupil extends Student {
private double chineseScore;
private double mathScore;
public Pupil(String name, int age, double chineseScore, double mathScore) {
super(name, age);
this.type = "小学生";
this.chineseScore = chineseScore;
this.mathScore = mathScore;
}
@Override
public double total() {
return (this.chineseScore + this.mathScore) / 2;
}
@Override
public void getInfo() {
super.getInfo();
System.out.println("平均成绩:" + this.total());
}
}
// MiddleStudent类
public class MiddleStudent extends Student {
private double chineseScore;
private double mathScore;
private double englishScore;
public MiddleStudent(String name, int age, double chineseScore, double mathScore, double englishScore) {
super(name, age);
this.type = "中学生";
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
@Override
public double total() {
return (this.chineseScore + this.mathScore + this.englishScore) / 3;
}
@Override
public void getInfo() {
super.getInfo();
System.out.println("平均成绩:" + this.total());
}
}
// Undergraduate类
public class Undergraduate extends Student {
private double requiredCredit;
private double electiveCredit;
public Undergraduate(String name, int age, double requiredCredit, double electiveCredit) {
super(name, age);
this.type = "大学生";
this.requiredCredit = requiredCredit;
this.electiveCredit = electiveCredit;
}
@Override
public double total() {
return this.requiredCredit + this.electiveCredit;
}
@Override
public void getInfo() {
super.getInfo();
System.out.println("总学分:" + this.total());
}
}
// 测试代码
public class Test {
public static void main(String[] args) {
Pupil pupil = new Pupil("Tom", 10, 90, 95);
MiddleStudent middleStudent = new MiddleStudent("Jerry", 15, 85, 90, 95);
Undergraduate undergraduate = new Undergraduate("Lucy", 20, 90, 20);
pupil.getInfo();
middleStudent.getInfo();
undergraduate.getInfo();
System.out.println("总人数:" + Student.number);
}
}
```
以上代码实现了题目所要求的抽象类实现多态设计,可以根据输入的数据输出对应的学生信息,以及学生人数。
阅读全文