完成学生及教师的设计(包括集合) 分数 20 作者 陈海宁 单位 成都信息工程大学 已知Main类、Person类的设计,完成Student类,Teacher类、MyTool类的设计。
时间: 2024-11-20 20:34:24 浏览: 97
在设计这个系统时,首先我们需要明确几个基本类以及它们之间的关系。这里是一个简化的设计方案:
1. Person类(人员类): 这个类作为基础,包含一些通用属性,如姓名(name) 和ID(id),可能还会有共有的行为,比如获取姓名。
```java
public class Person {
private String name;
private int id;
public Person(String name, int id) {
this.name = name;
this.id = id;
}
// getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
}
```
2. Student类 (学生类): 继承自Person类,并添加特有的属性如学号(studentNum) 和课程成绩(grades)。可能需要实现Comparable接口来排序成绩。
```java
import java.util.List;
public class Student extends Person implements Comparable<Student> {
private int studentNum;
private List<Integer> grades;
public Student(String name, int id, int studentNum, List<Integer> grades) {
super(name, id);
this.studentNum = studentNum;
this.grades = grades;
}
// getters and setters
public int getStudentNum() { return studentNum; }
public void setStudentNum(int studentNum) { this.studentNum = studentNum; }
public List<Integer> getGrades() { return grades; }
public void setGrades(List<Integer> grades) { this.grades = grades; }
@Override
public int compareTo(Student other) {
return Integer.compare(this.getGrades().stream().mapToInt(Integer::intValue).sum(), other.getGrades().stream().mapToInt(Integer::intValue).sum());
}
}
```
3. Teacher类 (教师类): 同样继承自Person类,可能增加专业(profession) 属性和授课的班级(studentsTaught) 集合。
```java
import java.util.Set;
public class Teacher extends Person {
private String profession;
private Set<Student> studentsTaught;
public Teacher(String name, int id, String profession, Set<Student> studentsTaught) {
super(name, id);
this.profession = profession;
this.studentsTaught = studentsTaught;
}
// getters and setters
public String getProfession() { return profession; }
public void setProfession(String profession) { this.profession = profession; }
public Set<Student> getStudentsTaught() { return studentsTaught; }
public void addStudent Taught(Student student) { this.studentsTaught.add(student); }
}
```
4. MyTool类 (工具类): 可能用于辅助操作,例如计算平均成绩等。
```java
public class MyTool {
public static double calculateAverageGrade(Student student) {
if (student.getGrades() != null && !student.getGrades().isEmpty()) {
return student.getGrades().stream().mapToInt(Integer::intValue).average().orElse(Double.NaN);
} else {
throw new IllegalArgumentException("No grades available for the student.");
}
}
}
```
阅读全文