设计一个学生类Student,并派生出:小学生、中学生、大学生、研究生4个类;其中大学生类再派出一年级学生、二年级学生、三年级学生、四年级学生4个子类;研究生再派出硕士生和博士生两个子类,请自行设计他们的成员数量,编写完成他们之间的继承关系,测试并输出相关数据。
时间: 2024-11-11 10:23:37 浏览: 7
首先,我们需要定义一个基本的学生类`Student`,然后根据要求进行派生。以下是一个简单的例子:
```java
// 基础学生类 Student
public abstract class Student {
private String name;
private int age;
// 构造函数
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// 获取和设置名字
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 获取年龄
public int getAge() {
return age;
}
// 设置年龄(注意,年龄应保持合理范围)
public void setAge(int age) {
if (age >= 0 && age <= 100) {
this.age = age;
} else {
throw new IllegalArgumentException("Invalid age");
}
}
// 定义抽象方法,用于获取年级或阶段
public abstract String getGradeOrPhase();
// 打印基本信息
@Override
public String toString() {
return "Name: " + name + ", Age: " + age + ", Grade/Phase: " + getGradeOrPhase();
}
}
// 小学生、初中生、大学生和研究生类
public class PrimaryStudent extends Student {
public PrimaryStudent(String name, int age) {
super(name, age);
}
@Override
public String getGradeOrPhase() {
return "Primary";
}
}
public class JuniorHighStudent extends Student {
public JuniorHighStudent(String name, int age) {
super(name, age);
}
@Override
public String getGradeOrPhase() {
return "Junior High";
}
}
public class UndergraduateStudent extends Student {
// 不同年级的学生,比如一年级到四年级
private int year;
public UndergraduateStudent(String name, int age, int year) {
super(name, age);
this.year = year;
}
public int getYear() {
return year;
}
public void setYear(int year) {
if (year >= 1 && year <= 4) {
this.year = year;
} else {
throw new IllegalArgumentException("Invalid year for undergraduate student");
}
}
@Override
public String getGradeOrPhase() {
return "Undergraduate - Year " + year;
}
}
public class GraduateStudent extends Student {
// 硕士生和博士生
private String degree;
public GraduateStudent(String name, int age, String degree) {
super(name, age);
this.degree = degree;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
if (degree.equals("Master") || degree.equals("Doctor")) {
this.degree = degree;
} else {
throw new IllegalArgumentException("Invalid degree");
}
}
@Override
public String getGradeOrPhase() {
return "Graduate - " + degree;
}
}
```
为了测试这些类,你可以创建一个主类进行实例化并打印它们:
```java
public class Main {
public static void main(String[] args) {
Student primary = new PrimaryStudent("Tom", 7);
System.out.println(primary);
JuniorHighStudent juniorHigh = new JuniorHighStudent("Jerry", 13);
System.out.println(juniorHigh);
UndergraduateStudent undergraduate = new UndergraduateStudent("Spike", 18, 1);
System.out.println(undergraduate);
GraduateStudent master = new GraduateStudent("Tyke", 25, "Master");
System.out.println(master);
GraduateStudent doctor = new GraduateStudent("Butch", 30, "Doctor");
System.out.println(doctor);
}
}
```
运行这个`Main`类会输出每个学生的详细信息。
阅读全文