封裝(Encapsulation): 使用類來封裝學生的資訊和成績。
繼承(Inheritance): 雖然這個具體的場景可能不需要複雜的繼承結構,但我們會展示如何為未來可能的需求預留空間。
多態(Polymorphism): 我們將通過介面或抽象類展示多態的使用,以便未來可以容易地擴展功能。
設計思路
Student 類:代表單個學生,包含學生的基本資訊(如學號、姓名)和成績(國文和數學)。
Classroom 類:管理整個班級的學生資訊,包括添加學生和按學號讀入成績。
實現代碼
Student 類
java
Copy code
public class Student {
private String id; // 學號
private String name; // 姓名
private int chineseScore; // 國文成績
private int mathScore; // 數學成績
// 構造函數
public Student(String id, String name) {
this.id = id;
this.name = name;
}
// 封裝:屬性的 getters 和 setters
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChineseScore() {
return chineseScore;
}
public void setChineseScore(int chineseScore) {
this.chineseScore = chineseScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
}
Classroom 類
java
Copy code
import java.util.HashMap;
import java.util.Map;
public class Classroom {
private Map<String, Student> students; // 使用學號作為鍵來存儲學生對象
public Classroom() {
students = new HashMap<>();
}
// 添加學生
public void addStudent(Student student) {
students.put(student.getId(), student);
}
// 按學號更新學生的成績
public void updateScores(String id, int chineseScore, int mathScore) {
Student student = students.get(id);
if (student != null) {
student.setChineseScore(chineseScore);
student.setMathScore(mathScore);
} else {
System.out.println("Student with ID " + id + " not found.");
}
}
// 其他班級管理方法...
}
解決方案說明
Student 類封裝了單個學生的資訊和成績。
Classroom 類管理一個班級的學生,提供了添加學生和按學號更新成績的功能。
封裝:通過私有屬性和公開方法對學生資訊進行封裝,確保數據的安全性。
繼承和多態:雖然在這個簡單場景中我們沒有直接用到繼承和多態,但系統設計保留了這種可能性。例如,如果將來有不同類型的學生(如國際生或特殊需求學生),可以通過繼承Student類並覆寫相關方法來實現多態和特殊處理。
這個設計方案提供了一種結構化和靈活的方式來管理班級學生的成績,並且遵循了面向對象設計的主要原則。