定义Person的子类,如学生Student/教师Teacher/雇员Employee等
时间: 2024-10-05 10:03:34 浏览: 34
为了使`Person`抽象类更实际,我们可以为它创建多个子类,比如`Student`、`Teacher`和`Employee`,每个子类继承`Person`并实现`getCareer()`方法以表示特定的职业:
```java
// 学生类Student
public class Student extends Person {
// 添加可能特有的属性,如学号或专业
private String studentId;
private String major;
public Student(String name, String gender, int age, String studentId, String major) {
super(name, gender, age);
this.studentId = studentId;
this.major = major;
}
@Override
public String getCareer() {
return "学生";
}
// 如果需要,也可以添加更多的方法,例如显示学号或专业
public void displayExtraInfo() {
System.out.println("学号:" + studentId);
System.out.println("专业:" + major);
}
}
// 教师类Teacher
public class Teacher extends Person {
private String teacherId;
private String subject;
public Teacher(String name, String gender, int age, String teacherId, String subject) {
super(name, gender, age);
this.teacherId = teacherId;
this.subject = subject;
}
@Override
public String getCareer() {
return "教师";
}
public void displaySubject() {
System.out.println("教课科目:" + subject);
}
}
// 雇员类Employee
public class Employee extends Person {
private String employeeId;
private String jobTitle;
public Employee(String name, String gender, int age, String employeeId, String jobTitle) {
super(name, gender, age);
this.employeeId = employeeId;
this.jobTitle = jobTitle;
}
@Override
public String getCareer() {
return "员工";
}
public void displayJobTitle() {
System.out.println("职位:" + jobTitle);
}
}
```
这些子类都重写了父类`getCareer()`方法,提供了自己的职业描述,并可能还添加了额外的属性和展示方法。
阅读全文