Java 学生的属性:姓名、性别、年龄、学号、年级、专业:学生的行为:吃饭、娱乐、学习、写作业、 教师的属性:姓名、性别、年龄、工号、职称、部门:教师的行为:吃饭、娱乐、授课、改作业。 请设计出对应的继承体系,并在主类中完成测试
时间: 2023-09-18 17:14:29 浏览: 236
首先,我们可以设计出一个人(Person)类,它包含姓名、性别、年龄三个属性,以及吃饭和娱乐两个行为。
```java
public class Person {
private String name;
private String gender;
private int age;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void entertain() {
System.out.println(name + " is entertaining.");
}
}
```
然后,我们可以设计出一个学生(Student)类,它继承自人(Person)类,增加了学号、年级、专业三个属性,以及学习和写作业两个行为。
```java
public class Student extends Person {
private String id;
private String grade;
private String major;
public Student(String name, String gender, int age, String id, String grade, String major) {
super(name, gender, age);
this.id = id;
this.grade = grade;
this.major = major;
}
public void study() {
System.out.println(name + " is studying.");
}
public void doHomework() {
System.out.println(name + " is doing homework.");
}
}
```
最后,我们可以设计出一个教师(Teacher)类,它也继承自人(Person)类,增加了工号、职称、部门三个属性,以及授课和改作业两个行为。
```java
public class Teacher extends Person {
private String jobNumber;
private String title;
private String department;
public Teacher(String name, String gender, int age, String jobNumber, String title, String department) {
super(name, gender, age);
this.jobNumber = jobNumber;
this.title = title;
this.department = department;
}
public void teach() {
System.out.println(name + " is teaching.");
}
public void gradeHomework() {
System.out.println(name + " is grading homework.");
}
}
```
接下来,我们可以在主类中进行测试:
```java
public class Main {
public static void main(String[] args) {
Student student = new Student("Tom", "Male", 18, "001", "Freshman", "Computer Science");
student.eat();
student.entertain();
student.study();
student.doHomework();
Teacher teacher = new Teacher("Mary", "Female", 35, "1001", "Associate Professor", "Computer Science");
teacher.eat();
teacher.entertain();
teacher.teach();
teacher.gradeHomework();
}
}
```
输出结果如下:
```
Tom is eating.
Tom is entertaining.
Tom is studying.
Tom is doing homework.
Mary is eating.
Mary is entertaining.
Mary is teaching.
Mary is grading homework.
```
阅读全文