要求:Person类的成员方法是输出自己的姓名和年龄;
Student 类中重写Person的成员方法输出自己的姓名、年龄和学号,实现接口计算英语,语文,数学三门课成绩;
增加一个computerStudent 类继承Student类,并重写成员方法,输出自己的姓名、年龄、学号、班级。接口方法计算英语,语文,数学JAVA、C语言、计算机基础六门课的成绩。
参考下 https://blog.csdn.net/lf1949/article/details/116136974
首先为Student类添加输出学号和三门课成绩的方法,可以在Student类中添加如下代码:
public class Student extends Person {
//...
private String studentID;
private int score1, score2, score3;
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public void setScores(int score1, int score2, int score3) {
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
}
public void printInfo() {
System.out.println("Student ID: " + studentID);
System.out.println("Score 1: " + score1);
System.out.println("Score 2: " + score2);
System.out.println("Score 3: " + score3);
}
}
然后让ComputerStudent继承自Student类并重新实现输出班级和六门课成绩的方法,可以在ComputerStudent类中添加如下代码:
public class ComputerStudent extends Student {
//...
private String className;
private int score4, score5, score6;
public void setClassName(String className) {
this.className = className;
}
public void setScores(int score1, int score2, int score3, int score4, int score5, int score6) {
super.setScores(score1, score2, score3);
this.score4 = score4;
this.score5 = score5;
this.score6 = score6;
}
public void printInfo() {
super.printInfo();
System.out.println("Class name: " + className);
System.out.println("Score 4: " + score4);
System.out.println("Score 5: " + score5);
System.out.println("Score 6: " + score6);
}
}
可以看到,这里重新声明了一个新的setScores方法,用super调用了父类的setScores方法来初始化父类继承的三门课的成绩,然后为子类新增的三门课成绩赋值,最终在printInfo方法中依次输出学号、三门课程、班级和三门课程。