如何定义继承关系?为"学生"类派生出"小学生""中学生""大学生""研究生"四个类,其中"研究生"类再派生出"硕士生"和"博士生"两个子类。
时间: 2023-10-10 11:14:51 浏览: 97
继承关系是指一个类从另一个类中继承属性和方法的过程。在Java中,使用关键字"extends"来定义继承关系。子类可以继承父类的非私有成员变量和方法,并且可以通过super关键字访问父类的构造函数和方法。
下面是根据题目要求定义的"学生"类和其派生类的实现代码:
```java
class Student {
protected String name;
protected int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void study() {
System.out.println("I am studying.");
}
}
class PrimaryStudent extends Student {
public PrimaryStudent(String name, int age) {
super(name, age);
}
public void play() {
System.out.println("I am playing.");
}
}
class MiddleStudent extends Student {
public MiddleStudent(String name, int age) {
super(name, age);
}
public void sleep() {
System.out.println("I am sleeping.");
}
}
class CollegeStudent extends Student {
public CollegeStudent(String name, int age) {
super(name, age);
}
public void work() {
System.out.println("I am working.");
}
}
class GraduateStudent extends CollegeStudent {
public GraduateStudent(String name, int age) {
super(name, age);
}
@Override
public void study() {
System.out.println("I am studying in the graduate program.");
}
}
class MasterStudent extends GraduateStudent {
public MasterStudent(String name, int age) {
super(name, age);
}
public void research() {
System.out.println("I am doing research.");
}
}
class DoctorStudent extends GraduateStudent {
public DoctorStudent(String name, int age) {
super(name, age);
}
public void publishPaper() {
System.out.println("I am publishing a research paper."); }
}
```
以上代码中,"学生"类是基类,"小学生"、"中学生"、"大学生"和"研究生"是派生类。其中,"研究生"类又派生出了"硕士生"和"博士生"两个子类。
阅读全文