2.编写一个类Student,该类拥有属性:校名、学号、性别、出生日期。方法包含设置姓名和成绩(setName(),setScore()),再编写Student类的子类Undergraduate(大学
时间: 2024-10-21 20:17:37 浏览: 61
当然可以。首先,我们创建一个名为`Student`的基本类,用于存储学生的基本信息:
```java
public class Student {
private String schoolName;
private int studentID;
private String gender;
private Date birthDate;
// 默认构造函数
public Student(String schoolName) {
this.schoolName = schoolName;
}
// 属性访问器和设置器
public void setName(String name) {
this.name = name;
}
public void setScore(int score) {
// 这里假设score是一个整数范围内的值,具体实现可能会更复杂
if (score >= 0 && score <= 100) {
this.score = score;
} else {
throw new IllegalArgumentException("Score must be between 0 and 100.");
}
}
// getter methods for accessing the properties
public String getSchoolName() {
return schoolName;
}
public int getStudentID() {
return studentID;
}
public String getGender() {
return gender;
}
public Date getBirthDate() {
return birthDate;
}
// 省略setters for gender and birthDate for brevity
}
```
接着,我们创建一个名为`Undergraduate`的子类,它继承自`Student`并可能添加特定于大学生的功能:
```java
public class Undergraduate extends Student {
private String major; // 专业
private double gpa; // 平均绩点
// 子类特有的构造函数,需要包含基本类的所有参数
public Undergraduate(String schoolName, String major, int studentID, String gender, Date birthDate) {
super(schoolName);
this.major = major;
this.studentID = studentID;
this.gender = gender;
this.birthDate = birthDate;
}
// 如果有特殊的设置方法,例如设置平均绩点
public void setGPA(double gpa) {
if (gpa >= 0.0 && gpa <= 4.0) {
this.gpa = gpa;
} else {
throw new IllegalArgumentException("GPA must be between 0.0 and 4.0.");
}
}
// getter method for major
public String getMajor() {
return major;
}
// getter method for GPA
public double getGPA() {
return gpa;
}
}
```
阅读全文