写出完整代码并且注释
时间: 2024-09-13 11:13:22 浏览: 40
在这个示例中,我会为你展示一个简单的Java代码片段,这是一个基于上述人事管理系统的例子,使用了继承和多态的概念。首先,我们定义一个通用的`PersonClass`,然后创建`TeacherClass`和`StudentClass`作为其子类。
```java
// 定义通用人员类PersonClass
class PersonClass {
private String id;
private String name;
private String gender;
private Date birthDate;
// 构造函数和getter/setter
public PersonClass(String id, String name, String gender, Date birthDate) {
this.id = id;
this.name = name;
this.gender = gender;
this.birthDate = birthDate;
}
// getters and setters (省略)
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", gender=" + gender + ", birthDate=" + birthDate + "]";
}
}
// 定义教师类TeacherClass,继承自PersonClass
class TeacherClass extends PersonClass {
private String department; // 部门
private String title; // 职称
private double salary; // 工资
// 构造函数
public TeacherClass(String id, String name, String gender, String department, String title, double salary) {
super(id, name, gender, birthday); // 调用父类构造函数
this.department = department;
this.title = title;
this.salary = salary;
}
// getters and setters (省略)
// 用于演示多态性的toString方法
@Override
public String toString() {
return "Teacher [" + super.toString() + ", department=" + department + ", title=" + title + ", salary=" + salary + "]";
}
}
// 定义学生类StudentClass,继承自PersonClass
class StudentClass extends PersonClass {
private int collegeScore; // 高考分数
private String major; // 所学专业
// 构造函数
public StudentClass(String id, String name, String gender, String major, int collegeScore) {
super(id, name, gender, birthday); // 调用父类构造函数
this.major = major;
this.collegeScore = collegeScore;
}
// getters and setters (省略)
// 同样用于演示多态性的toString方法
@Override
public String toString() {
return "Student [" + super.toString() + ", major=" + major + ", collegeScore=" + collegeScore + "]";
}
}
// 在主类中测试
public class MainClass {
public static void main(String[] args) {
// 创建并打印TeacherClass对象
TeacherClass teacher = new TeacherClass("T001", "张三", "男", "IT部", "教授", 5000);
System.out.println(teacher);
// 创建并打印StudentClass对象
StudentClass student = new StudentClass("S001", "李四", "女", "数学系", 680);
System.out.println(student);
}
}
```
在这个例子中,`main`函数展示了如何创建`TeacherClass`和`StudentClass`的实例,并通过它们的`toString`方法展示了多态性,即虽然都是`PersonClass`类型的引用,但实际调用了对应子类的特定方法。注意,`super`关键字在这里用于调用父类的方法。
阅读全文